我是node.js的新手,并且在Promises
方面遇到了麻烦。我想通过使用Promises
逐步构建/构建结果变量。
我“抽象”了我的代码只是为了更好地指出问题。基本上,我想做的是创建一个包含多个rest api调用的结果模型(可以并行完成的那些调用在Promise.all
中进行调用。)
谢谢。
function test() {
var result = {};
var prom1 = new Promise(function(resolve, reject) {
resolve(addTwo(result));
}).catch(err => console.log(err));
return prom1.then(function(result) {
promises = [];
promises.push(new Promise(function(resolve, reject) {
resolve(addD(result));
}));
promises.push(new Promise(function(resolve, reject) {
resolve(addC(result));
}));
Promise.all(promises)
.then(result)
}).then(console.log(result)); //logging because I was testing
}
function addTwo(result) {
result.a = "a";
result.b = "b";
return result;
}
function addD(result) {
result.d = "d";
}
function addC(result) {
result.c = "c";
}
test();
期望的输出是:{ a: 'a', b: 'b', d: 'd', c: 'c' }
,但是我得到了:{ a: 'a', b: 'b' }
我了解,如果我在then()
上调用Promise
,则可以在该块中访问promise的返回值,但是我可以通过某种方式调整代码来“构建”然后使用Promise.all在then调用中调用result变量?
答案 0 :(得分:1)
return
Promise.all(promises)
,以便其结果链接到您有then
的{{1}}。console.log(result)
行有错误,您将Promise.all(promises).then(result)
传递给result
,但是then
期望函数作为参数,而不是对象考虑使用then
,因为它比这些async/await
链更容易混淆
答案 1 :(得分:0)
使用异步/等待语法以更ES8的方式可以避免.then()。catch()的麻烦。我觉得以这种方式更容易实现承诺。
async function test() {
try {
let result = {}
await new Promise(function(resolve, reject) {
resolve(addTwo(result))
})
let promises = []
promises.push(new Promise(function(resolve, reject) {
resolve(addD(result))
}))
promises.push(new Promise(function(resolve, reject) {
resolve(addC(result))
}))
await Promise.all(promises)
return result
} catch (e) {
console.error(e)
}
}
请注意,您必须等待测试功能结果