Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from a promise with node.js without .then function

I have a problem with a promise using node.js. My code is below:

var p1 = new Promise(function(resolve, reject) {
  // my function here
});

p1.then(function(result){
  // my result
});

This code works but to get values from p1 I must use the .then method and my result values can be accessed just on p1.then. How do I access p1 values without .then?

Below are my expected results:

var p1 = new Promise(function(resolve, reject) {
      // my function here
    });

var abc = NextFunction(p1);

The p1 values will be used afterwards in code outside of the p1 variable.

like image 211
monoy suronoy Avatar asked Dec 21 '15 09:12

monoy suronoy


People also ask

How do I return a value from promise TypeScript?

To access the value of a promise in TypeScript, call the then() method on the promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value as a parameter.

How do you deal with promises in Node?

The promise is resolved by calling resolve() if the promise is fulfilled, and rejected by calling reject() if it can't be fulfilled. Both resolve() and reject() takes one argument - boolean , string , number , array , or an object .


2 Answers

p1 is a Promise, you have to wait for it to evaluate and use the values as are required by Promise.

You can read here: http://www.html5rocks.com/en/tutorials/es6/promises/

Although the result is available only inside the resolved function, you can extend it using a simple variable

var res;
p1.then(function(result){
    res = result; // Now you can use res everywhere
});

But be mindful to use res only after the promise resolved, if you depend on that value, call the next function from inside the .then like this:

var res;
p1.then(function(result){
    var abc = NextFunction(result);
});
like image 102
AlexD Avatar answered Oct 22 '22 20:10

AlexD


You can use await after the promise is resolved or rejected.

function resolveAfter2Seconds(x) { 
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x);
        }, 2000);
    });
}

async function f1() {
    var x = await resolveAfter2Seconds(10);
    console.log(x); // 10
}

f1();

Be aware await expression must be inside async function though.

like image 29
toadead Avatar answered Oct 22 '22 21:10

toadead