嗨,我需要一个接一个地执行promise,我如何使用promise来实现这一点。所有帮助都会很棒。以下是我当前正在使用的代码示例,但由于它是并行执行的,因此搜索将无法正常工作
public testData: any = (req, res) => {
// This method is called first via API and then promise is triggerd
var body = req.body;
// set up data eg 2 is repeated twice so insert 2, 5 only once into DB
// Assuming we cant control the data and also maybe 3 maybe inside the DB
let arrayOfData = [1,2,3,2,4,5,5];
const promises = arrayOfData.map(this.searchAndInsert.bind(this));
Promise.all(promises)
.then((results) => {
// we only get here if ALL promises fulfill
console.log('Success', results);
res.status(200).json({ "status": 1, "message": "Success data" });
})
.catch((err) => {
// Will catch failure of first failed promise
console.log('Failed:', err);
res.status(200).json({ "status": 0, "message": "Failed data" });
});
}
public searchAndInsert: any = (data) => {
// There are database operations happening here like searching for other
// entries in the JSON and inserting to DB
console.log('Searching and updating', data);
return new Promise((resolve, reject) => {
// This is not an other function its just written her to make code readable
if(dataExistsInDB(data) == true){
resolve(data);
} else {
// This is not an other function its just written her to make code readable
insertIntoDB(data).then() => resolve(data);
}
});
}
我在Google中抬头看了看,发现reduce将有所帮助,我将非常感谢您提供任何有关如何将其转换为reduce的帮助,或者您建议的任何方法(.map中的并发均无效)
答案 0 :(得分:1)
很遗憾,该承诺不允许对他们的流程进行任何控制。这意味着->创建新的Promise后,它将按自己的意愿进行异步处理。
Promise.all
不会更改它,它的唯一目的是检查您放入其中的所有诺言,并在所有诺言完成(或其中一个失败)后予以解决。
为了能够创建和控制异步流,最简单的方法是将Promise的创建包装到函数中并创建某种工厂方法。然后,无需先创建所有承诺,而仅在需要时创建一个承诺,等到解决它并以相同的方式继续执行即可。
async function doAllSequentually(fnPromiseArr) {
for (let i=0; i < fnPromiseArr.length; i++) {
const val = await fnPromiseArr[i]();
console.log(val);
}
}
function createFnPromise(val) {
return () => new Promise(resolve => resolve(val));
}
const arr = [];
for (let j=0; j < 10; j++) {
arr.push(createFnPromise(Math.random()));
}
doAllSequentually(arr).then(() => console.log('finished'));
PS:使用标准的Promise链也可以不进行异步/等待,但是它需要递归实现。