node.js - 如何将对象或变量与 Promise.all 一起传递?

标签 node.js promise

我遇到了一个问题,我想向 Plaid 发送一些请求以获取帐户信息,但当请求返回时,我不知道在哪里关联帐户信息,因此我需要传递一个 ID,例如 source.id。问题是 Promise.all 不适用于我在下面编写的内容。有没有其他方法可以实现此目的,以便我可以取回我需要的 ID?

var userSources = firestore.collection('sources');
    userSources.get().then(snapshot => {
        snapshot.forEach(doc => {
            var source = doc.data();
            sources.push(source);
        });
    return sources;

    }).then((sources) => {
        // 2: Connect to Plaid and query accounts
        var promises = [];
        sources.forEach(function(source) {
            promises.push({
                id: source.id,
                p: client.getBalance(source.access_token)
            });
        });
        return Promise.all(promises);

    }).then...
    ```

最佳答案

如果您想最终得到一个包含 idbalance 的对象数组,您可以执行类似的操作。您调用 client.getBalance() 并在 .then() 处理程序中创建您想要的对象,该对象将 source.idbalance 组合在一起,并将其作为 Promise 的解析值返回。然后,您可以对该 Promise 数组运行 Promise.all() 并获取适当的对象数组作为结果。

let userSources = firestore.collection('sources');
userSources.get().then(snapshot => {
    return Promise.all(snapshot.map(doc => {
        let source = doc.data();
        return client.getBalance(source.access_token).then(balance => {
            return {id: source.id, balance: balance};
        });
    }));
}).then(results => {
    // array of {id, balance} objects
    console.log(results);
});

这样做的一个优点是,它将余额和相应的 id 放在同一个对象数组中,而不是放在单独的数组中。

关于node.js - 如何将对象或变量与 Promise.all 一起传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60163471/

相关文章:

node.js - 将二进制音频文本转换为音频文件

javascript - 在 Electron 中获取剪贴板类型

javascript - promise 条件相等

node.js - 不太了解 Q Promise 库

javascript - 内存与重复的 promise

javascript - 如何在 html 文件中包含 nodejs 模块?

node.js - 将 nginx 放在 nodejs 前面来服务静态 Assets 是否合理?

typescript - 带有 readline(询问者)问题的异步/等待循环

javascript - Node.js 的故障 promise 复制值

javascript - 使用 vhost 中间件在 Express 中按子域指定路由