如何使用没有 .then 函数的 node.js 从 promise 中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34392691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get values from a promise with node.js without .then function
提问by monoy suronoy
I have a problem with a promise using node.js. My code is below:
我对使用 node.js 的承诺有问题。我的代码如下:
var p1 = new Promise(function(resolve, reject) {
// my function here
});
p1.then(function(result){
// my result
});
This code works but to get values from p1I must use the .thenmethod and my result values can be accessed just on p1.then. How do I access p1values without .then?
此代码有效,但要从中获取值,p1我必须使用该.then方法,并且我的结果值只能在p1.then. 如何在p1没有 的情况下访问值.then?
Below are my expected results:
以下是我的预期结果:
var p1 = new Promise(function(resolve, reject) {
// my function here
});
var abc = NextFunction(p1);
The p1values will be used afterwards in code outside of the p1variable.
该p1值将随后在的代码之外使用p1变量。
回答by AlexD
p1 is a Promise, you have to wait for it to evaluate and use the values as are required by Promise.
p1 是 a Promise,您必须等待它评估并使用 Promise 要求的值。
You can read here: http://www.html5rocks.com/en/tutorials/es6/promises/
你可以在这里阅读:http: //www.html5rocks.com/en/tutorials/es6/promises/
Although the resultis available only inside the resolved function, you can extend it using a simple variable
尽管result仅在已解析的函数中可用,但您可以使用一个简单的变量来扩展它
var res;
p1.then(function(result){
res = result; // Now you can use res everywhere
});
But be mindful to use resonly after the promise resolved, if you depend on that value, call the next function from inside the .thenlike this:
但是请注意res仅在 promise 解决后才使用,如果您依赖于该值,请从内部调用 next 函数,.then如下所示:
var res;
p1.then(function(result){
var abc = NextFunction(result);
});
回答by toadead
You can use await after the promise is resolved or rejected.
您可以在承诺解决或拒绝后使用 await。
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 awaitexpression must be inside asyncfunction though.
请注意await表达式必须在async函数内部。
回答by Sunding Wei
You can do this, using the deasyncmodule
您可以使用deasync模块执行此操作
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);
}

