我现在有点陷入竞争状态,我把头发拉了出来。基本上,我查询API,将结果添加到数据库,然后使用返回/保存的数据执行操作。
我对这个具体问题的了解较少,更多的是如何解决这类问题的设计模式。第p.push(formatter.createAccounts(account, id));
行可能会运行1000次,可能需要20秒左右。
关于我做错的任何想法都会非常有帮助
谢谢, 奥利
// get all users
Promise.all(updatedUsers)
.then(() => {
// create an array of promises
const p = [];
users.then((user) => {
...
ids.forEach((id) => {
const accounts = foo.getAccounts(id, true); // returns a promise
accounts.then((account) => {
// add the return data from here to the promise array at the bottom
p.push(formatter.createAccounts(account, id));
});
});
});
// this would ideally be a promise array of the data from above - but instead it just evaluates to [] (what it was set to).
Promise.all(p).then(() => {
// do my stuff that relies on the data here
})
});
答案 0 :(得分:2)
问题是您没有将foo.getAccounts
承诺包含在promises数组中。修改版:
Promise.all(updatedUsers)
.then(() => {
users.then((user) => {
return Promise.all(ids.map(id => {
//for each ID we return a promise
return foo.getAccounts(id, true).then(account => {
//keep returning a promise
return formatter.createAccounts(account, id)
})
}).then((results) => {
//results is an array of the resolved values from formatter.createAccounts
// do my stuff that relies on the data here
})
})
//rest of closing brackets