简体   繁体   中英

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?

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.

componentDidMount() {
  this.getLists();
}

async getLists() {     
  const data = await Promise.all([api.get('/url/1'),api.get('/url/2')]);
  console.log('1st API Response ----> ',data[0].body);
  console.log('2nd API Response ----> ',data[1].body);
}

So your aim to execute both in parallel is now satisfied. Promise.all([]) does that. Now since Promise.all returns a promise, you can await it.

Please dont forget to wrap your function in try/catch block

In your first code, only the tasks within the then block of the first API call are executed after API call task is completed, however other lines of code is executed. Similarly for the second API call.

In your second code,

var res = await api.get('/url/1');

The await API call blocks any code after it to be executed unless its job is completed.

You can do the following:

async function getLists() {

  const [res, res2] = await Promise.all([
    api.get('url/1'),
    api.get('url/2')
  ])

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM