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

我只是一个虾纸丫 提交于 2021-02-07 11:24:21

问题


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.


回答1:


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);
});



回答2:


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.




回答3:


You can do this, using the deasync module

var node = require("deasync");

// Wait for a promise without using the await
function wait(promise) {
    var done = 0;
    var result = null;
    promise.then(
        // on value
        function (value) {
            done = 1;
            result = value;
            return (value);
        },
        // on exception
        function (reason) {
            done = 1;
            throw reason;
        }
    );

    while (!done)
        node.runLoopOnce();

    return (result);
}

function test() {
    var task = new Promise((resolve, reject)=>{
        setTimeout(resolve, 2000, 'Hello');
        //resolve('immediately');
    });

    console.log("wait ...");
    var result = wait(task);
    console.log("wait ...done", result);
}


来源:https://stackoverflow.com/questions/34392691/how-to-get-values-from-a-promise-with-node-js-without-then-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!