The general idea of async/wait
is to reduce code and make it less noisy.
Usually with the promises, the method then()
is used to wait for the answer:
$http.get(url).then(function(){
//..
});
This translates to:
var response = await $http.get(url);
Imagine now having to wait for an asynchronous process to run another asynchronous process:
$http.get(url).then(function(response){
//...
$http.get(url + response.data.id).then(function(){
console.log(response2.data.message);
});
});
And with async / await it would be:
var response = await $http.get(url);
var response2 = await $http.get(url + response.data.id);
console.log(response2.data.message);
asyn / await also helps avoid the callback hell and makes the code less noisy in the sense that since the code follows a line constant execution, makes it easier to maintain it.
Note: As already mentioned, you can only use await
within a function marked as async
.