首页 > 解决方案 > 使用 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 来“构建”结果变量观点?

标签: node.jsasynchronouspromise

解决方案


  1. 你需要return你的Promise.all(promises),以便它的结果被链接到then你所拥有的地方console.log(result)
  2. 我相信你在这行有一个错误Promise.all(promises).then(result),你传递resultthenthen期望一个函数作为参数,而不是一个对象

考虑使用async/await因为它比这些Promise链更容易混淆


推荐阅读