node.js - 使用 node.js Promises 正确构造返回值
问题描述
我是 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()
a Promise
,我将在该块中访问 promise 的返回值,但是我可以以某种方式调整我的代码以在 then 调用中使用 Promise.all 来“构建”结果变量观点?
解决方案
- 你需要
return
你的Promise.all(promises)
,以便它的结果被链接到then
你所拥有的地方console.log(result)
。 - 我相信你在这行有一个错误
Promise.all(promises).then(result)
,你传递result
给then
但then
期望一个函数作为参数,而不是一个对象
考虑使用async/await
因为它比这些Promise
链更容易混淆
推荐阅读
- java - 创建 jfreechart 分数条/图表的问题
- php - 在 localhost 上工作时的相对 URL
- c - 在 C 程序中,无法通过 Windows (Netbeans) 中的键盘指示 EOF
- javascript - 如何在angular2中获取html元素的宽度?
- android - string.xml 的图标已更改
- node.js - nodejs以同步方式创建目录不可靠
- html - 了解引导程序
- laravel-5 - Laravel 5.4:过滤并满足请求中的所有参数
- javascript - 如何确定组件是否包含 React 层次结构
- java - 如何在 Maven 中的 Eclipse 中添加球衣原型?