1

There are many questions on making a Nodejs/Javascript method synchronous, but the answers I have seen so far involved using libraries such as async and fibrous.

But to use libraries such as fibrous, I have to wrap my function with their wrapper.

I am seeking a solution where the code lies within my function (not outside and wrapping it).

For example, this is my async function which uses a callback:

function myFunc(callback) {
  // Classic database fetch which is asynchronous
  db.find("foo", function(err, results) {
    callback(err, results);
  });
}

What I want is for the function to return the results:

function myFunc() {
  // Make this function synchronous, and return the result
  // ...

  return results;
}

How do I do that?

Once again, I don't want to wrap myFunc with other functions. I am thinking if a sleep loop works?

samwize
  • 25,675
  • 15
  • 141
  • 186

2 Answers2

2

No, you can't use a loop to wait for an asynchronous call. Javascript is single threaded, so you need to return control to the main event handler for the asynchronous callback to be called. If you run a loop, the event that the database query is completed will just wait in the queue and never be handled.

What you can do is to return a promise instead of the result itself. That's an object that keeps track of whether the callback has been called or not, has a property where the callback can put the result, and has a method for getting the result when you need it (which uses a callback, because once you use an asynchrous method it can't be handled completely syncronously).

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

If you want an actual return value from an asynchronous function, you have no other choice than using either generators or Promises. You will always have to wrap your functions, or return Promises directly.

One of the best promise libraries out there is bluebird, which also has an explanation for how and why to use it (https://github.com/petkaantonov/bluebird#what-are-promises-and-why-should-i-use-them). If you need to interface with node style callbacks or need to expose an API that relies on node style callbacks instead of promises, it also comes with some convenience methods for automating that conversion.

Tim
  • 2,430
  • 19
  • 20