Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a promise to be resolved?

I'm dealing with a NodeJs framework that requires a certain function to be synchronous, but I need to retrieve a value that can only be accessed asynchronously. In a perfect world, I would be able to return a promise, but I can't.

As a quick-and-dirty solution, I created the following method:

exports.synchronizePromise = function(promise) {     var value;     promise.then(function(promiseValue) {         value = promiseValue;     });     while (!value) {} // Wait for promise to resolve     console.log("DONE: " + value); // Never reached     return value; }; 

But I get an error. Is there any way to accomplish what I need?

like image 422
sinθ Avatar asked Jun 11 '14 18:06

sinθ


People also ask

How do you wait until a promise is resolved?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function. Copied!

How do you await a promise?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do you wait for setTimeout to finish?

Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.


2 Answers

Given that node is by default only single threaded there isn't really an easy way to solve this. There is one though. Bases on generators/fibers you can add a sort of concurrent execution to node. There is a waitfor implementation based on that.

like image 58
tcurdt Avatar answered Oct 05 '22 12:10

tcurdt


In Q if you have a resolved promise you can just take the value with inspect

exports.synchronizePromise = function(promise) {   var i = promise.inspect();     if (i.state === "rejected") {       throw i.reason;     } else if (i.state === "fulfilled") {       return i.value;     } else {       throw new Error("attempt to synchronize pending promise")     } }; 

However if the promise is pending, it is truly asynchronous and your question doesn't then make sense and the function will throw an error.

like image 35
Esailija Avatar answered Oct 05 '22 12:10

Esailija