Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Synchronise Promise Objects?

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.

like image 577
Burak Karasoy Avatar asked Aug 29 '16 18:08

Burak Karasoy


1 Answers

async promiseController(){
  for(const value of array) {
    console.log((await this.getVal(value))+'prom');
  }
}

No need to overcomplicate things. Just call await inside the loop and it'll wait for what you want.

As the other answer rightfully said - a promise represents a value and not an operation. For operations regular functions are used.

If you want to ignore failures you can .catch(() => {}) on the promise. If you want to retry until failures - you can refactor retry to a function and use that:

const retry = fn => (...args) => fn(...args).catch(retry(fn));
like image 124
Benjamin Gruenbaum Avatar answered Oct 01 '22 10:10

Benjamin Gruenbaum