且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用没有 .then 函数的 node.js 从 promise 中获取值

更新时间:2023-11-14 09:33:52

p1 是一个 Promise,你必须等待它评估并使用 Promise 要求的值.

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

您可以在这里阅读:http://www.html5rocks.com/en/教程/es6/promises/

尽管 result 仅在已解析的函数中可用,但您可以使用一个简单的变量对其进行扩展

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

但是请注意,只有在 promise 解决后才使用 res,如果您依赖该值,请从 .then 内部调用下一个函数,如下所示:>

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