我遇到了一个问题,我想向 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...
```
最佳答案
如果您想最终得到一个包含 id
和 balance
的对象数组,您可以执行类似的操作。您调用 client.getBalance()
并在 .then()
处理程序中创建您想要的对象,该对象将 source.id
与 balance
组合在一起,并将其作为 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/