我在构建异步代码时遇到了问题。所有数据库操作都是异步并返回Promises。
我需要在数据库中找到一堆项目,更改它们,然后保存它们,并且只有在保存之后,继续我的程序流程中的下一步。
我如何使用ES6承诺来解决这个问题?
以下是一些说明我问题的伪代码:
database.find("Items").then(results => {
results.forEach(result => {
result.name = "some different name";
database.save(result) // <-- is also async as find
});
return true;
}).then(next) {
// Only start here after all database.save() have been resolved
});
答案 0 :(得分:1)
您可以使用Promise.all()
:
database.find("Items").then(results => {
return Promise.all(results.map(result => {
result.name = "some different name";
return database.save(result) // <-- is also async as find
}));
}).then(() => {
// Only start here after all database.save() have been resolved
});
答案 1 :(得分:1)
使用Promise.all
等待多个承诺 - 它需要一个承诺的数组(可变长度)。
database.find("Items").then(results => {
var promises = results.map(result => {
// ^^^
result.name = "some different name";
return database.save(result);
// ^^^^^^
});
return Promise.all(promises);
}).then(saves => {
// ^^^^^ an array of the results from the save operations
…; // starts after all database.save() promises have been resolved
});