我正在尝试使用 Bluebird 库为 nodejs 编写一个 promise 函数。我想从我的函数中返回 2 个变量。 我希望第一个函数立即返回,第二个函数在返回前完成自己的 promise 链。
function mainfunction() {
return callHelperfunction()
.then(function (data) {
//do something with data
//send 200 Ok to user
})
.then(function (data2) {
//wait for response from startthisfunction here
})
.catch(function (err) {
//handle errors
});
}
function callHelperfunction() {
return anotherHelperFunction()
.then(function (data) {
return data;
return startthisfunction(data)
.then(function () {
//do something more!
})
});
}
最佳答案
就像普通函数只有一个返回值一样,同样的类比,promises 也只能用一个值解析。
就像常规函数一样,您可以从 promise 返回一个复合值,如果您返回一个数组,您也可以使用 .spread
轻松使用它:
Promise.resolve().then(function(el){
return [Promise.resolve(1), Promise.delay(1000).return(2));
}).spread(function(val1, val2){
// two values can be accessed here
console.log(val1, val2); // 1, 2
});
关于javascript - 使用 Bluebird promise 返回 2 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31590842/