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.
Promise.all()
or if you want your promises to do more of a Waterfall type thing. – Stakhanovism.then()
, named functions, to call function until each step returns resolved promise – Lastminute