Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - async await vs promise callback

I am doing a code change to convert .then(func{}) style code to async await.

In my example, converting from then to async await, removes the ability to query the API in parallel and process them in the order the request finished as two requests are independent from each other.

Is this a valid difference between the two syntaxes or is it just a matter of breaking two functions into two individual async functions that will make them run in parallel?

Sample code before upgrade:

componentDidMount() {
  this.loadLists();
}

loadLists() {
  console.log('start 1');
  api.get('/url/1').then(function(r) {
    console.log('done 1', r.body);
  });
  
  console.log('start 2');
  api.get('/url/2').then(function(r) {
    console.log('done 2', r.body);
  });
}

//OUTPUT
//start 1
//start 2
//done 1
//done 2

Sample code after upgrade:

componentDidMount() {
  this.getLists();
}

async getLists() {
  console.log('start 1');
  var res = await api.get('/url/1');
  console.log('done 1', res.body);
  console.log('start 2');
  var res2 = await api.get('/url/2');
  console.log('done 2', res2.body);
}

//OUTPUT
//start 1
//done 1
//start 2
//done 2

EDIT:

If the functions are split into two, async loadList1(), async loadList2()

Is calling both functions without the word await a proper use, that will result in two requests being submitted (nearly) simultaneously?

like image 401
maxi C Avatar asked Nov 30 '22 08:11

maxi C


1 Answers

await is responsible for waiting until the promise is resolved. If you want the requests to run in parallel, you could simply kick of both of them and await them afterwards:

console.log('start 1');
var res = api.get('/url/1');
console.log('start 2');
var res2 = api.get('/url/2');
console.log('done 1', (await res).body);
console.log('done 2', (await res2).body);

But of course that still introduces some sequential dependency since you are always going to process res before res2.

If you have even more calls, Promise.all is still the way to go. Remember, async/await is just syntactic sugar for creating and resolving promises.

like image 81
Felix Kling Avatar answered Dec 05 '22 00:12

Felix Kling