Home > Enterprise >  Is there a difference between the two code codes?
Is there a difference between the two code codes?

Time:04-22

First Code

console.log('Start');  // output 1
await axios({
  method: 'post',
  url: '<HTTP_URL>'
  data: <SOME_DATA>,
}).then ((response) => {
  // Do something... It could take a few seconds.
  console.log(response); // output 2
});
console.log('End');  // output 3

Second Code

console.log('Start');  // output 1
await axios({
  method: 'post',
  url: '<HTTP_URL>'
  data: <SOME_DATA>,
}).then (async (response) => {
  // Do something... It could take a few seconds.
  console.log(response); // output 2
});
console.log('End');  // output 3

Can the difference in asynchronous operation be caused by 'async' keyword of callback method?

In my test, the both source codes showed the same result.

In the second source code, I thought 'await' would guarantee only the call of the async callback. However, it actually guaranteed the complete of the async callback.

Why if they do the same thing?

CodePudding user response:

The difference would be if you need to await for a certain function within the then block.

console.log('Start');  // output 1
await axios({
  method: 'post',
  url: '<HTTP_URL>'
  data: <SOME_DATA>,
}).then (async (response) => {
  // Do something... It could take a few seconds.
  await slowResponseFunction();
  console.log(response); // output 2
});
console.log('End');  // output 3
  • Related