I have promise objects which need to work synchronize. For example second promise shouldn't work before first one is done. If first one rejects first one has to be executed again.
I have implemented some examples.This one works well.
call getVal, wait 2000ms, return, i++, again call getVal .....
getVal() {
return new Promise(function(resolve, reject) {
setTimeout(function(){ resolve(19) }, 2000);
});
}
async promiseController(){
for(var i =0;i<5;i++)
{
var _val = await this.getVal()
console.log(_val+'prom');
}
}
But I need to control an array of promise objects. What I want to do is that I have a data and I divided it 5 pieces. After first part is processed(for example:sent to server) well I want to process second part otherwise I have to process first part again.
This is the prototype implementation I made
getVal() {
return new Promise(function(resolve, reject) {
setTimeout(function(){ resolve(19) }, 2000);
});
}
async promiseController(){
var proms=[]
for(var i =0;i<5;i++)
{
proms.push(this.getVal())
}
for(var i =0;i<5;i++)
{
var _val = await proms[i]
console.log(_val+'prom');
}
}
Promises objects in this code works sequentially. How can i fix the code below so that it works synchronous as first example.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…