admin管理员组

文章数量:1221400

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

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?

Share Improve this question edited Mar 21, 2018 at 6:36 B. Desai 16.4k5 gold badges28 silver badges47 bronze badges asked Sep 21, 2017 at 5:24 maxi Cmaxi C 1422 silver badges13 bronze badges 2
  • 1 You can use Promise.all two combine the requests to keep processing them in parallel. But if you want to do something as soon as one of them is finished you are better off handling the promises individually. There's no point in making it sequential if you don't need it to be. – Ingo Bürk Commented Sep 21, 2017 at 5:27
  • @IngoBürk If i do not need to do anything after both are completed, do I still need to call them using Promise.all or can i just call those functions without using await? – maxi C Commented Sep 21, 2017 at 5:33
Add a comment  | 

4 Answers 4

Reset to default 10

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

You can do the following:

async function getLists() {

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

}

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.

本文标签: nodejsJavascriptasync await vs promise callbackStack Overflow