I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.
The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc. Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.
Here is an example/pseudocode of how I have implemented a basic promise-
var myPromise = new Promise(
function (resolve,reject) {
var x = MyDataStore(myObj);
resolve(x);
});
myPromise.then(
function (x) {
init(x);
});
As time passed, I came across ECMAScript 7 features, and one of them being ASYNC
and AWAIT
keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await
. They seem to add great value to programming style.
Again, here is a pseudocode of how my async, await function looks like-
async function myAsyncFunction (myObj) {
var x = new MyDataStore(myObj);
return await x.init();
}
var returnVal = await myAsyncFunction(obj);
Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.
Why is async,await needed when promises do a similar job?
Does async,await solve a bigger problem? Or was it just a different solution to callback hell?
As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?
Additional notes:
I have been using async,awaits and promises in my React projects and Node.js modules extensively. React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.
Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?
async/await
simply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.
For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there's complex data manipulation and whatnot involved, it's easier to understand what's going on if the code simply looks as though it's synchronous (to put it another way, syntax in and of itself is a form of "incidental complexity" that async/await
can get around).
If you're interested to know, you can use a library like co
(alongside generators) to give the same sort of feel. Things like this have been developed to solve the problem that async/await
ultimately solves (natively).
Async/Await provide a much nicer syntax in more complex scenarios. In particular, anything dealing with loops or certain other constructs like try
/catch
.
For example:
while (!value) {
const intermediate = await operation1();
value = await operation2(intermediate);
}
This example would be considerably more convoluted just using Promises.
const getValue = value => value || operation1().then(operation2).then(getValue);
Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem? or was it just a different solution to callback hell? As I said earlier, I am able to use Promises and Async,Await to solve the same problem. Is there anything specific that Async Await solved?
The first things you have to understand that async
/await
syntax is just syntactic sugar which is meant to augment promises. In fact the return value of an async
function is a promise. async
/await
syntax gives us the possibility of writing asynchronous in a synchronous manner. Here is an example:
Promise chaining:
function logFetch(url) {
return fetch(url)
.then(response => response.text())
.then(text => {
console.log(text);
}).catch(err => {
console.error('fetch failed', err);
});
}
Async
function:
async function logFetch(url) {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('fetch failed', err);
}
}
In the above example the await
waits for the promise (fetch(url)
) to be either resolved or rejected. If the promise is resolved the value is stored in the response
variable, and if the promise is rejected it would throw an error and thus enter the catch
block.
We can already see that using async
/await
might be more readable than promise chaining. This is especially true when the amount of promises which we are using increases. Both Promise chaining and async
/await
solve the problem of callback hell and which method you choose is matter of personal preference.
Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch
.
I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples: 6 Reasons Why JavaScript Async/Await Blows Promises Away (Tutorial)
await/async are often referred to as syntactic sugar to promises and let us wait for something (e.g. an API call), giving us the illusion that it is synchronous in an actual asynchronous code, which is a great benefit.
The things you want to achieve with async/await is possible with promises (but without the advantages of async/await). Lets take an example with this code:
const makeRequest = () => //promise way
getJSON()
.then(data => {
return data
})
makeRequest();
const makeRequest = async () => { //async await way
const data = await getJSON();
return data;
}
makeRequest()
Why is async/await prefered over promises?
Concise and clean - We don’t have to write .then and create an anonymous function to handle the response, or give a name data to a variable that we don’t need to use. We also avoided nesting our code. async/await is a lot cleaner. Error handling - Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same try/catch format. Debugging - A really good advantage when using async/await is that it’s much easier to debug than promises for 2 reasons: 1) you can’t set breakpoints in arrow functions that return expressions (no body). 2) if you set a breakpoint inside a .then block and use debug shortcuts like step-over, the debugger will not move to the following .then because it only “steps” through synchronous code. Error stacks - The error stack returned from the promises chain gives us no idea of where the error occurred and can be misleading. async/await gives us the error stack from async/await points to the function that contains the error which is a really big advantage.
Await syntax is simply synchronous code because you have to wait until the promise is fulfilled or rejected. Actually code execution after await keyword will be suspended until the promise resolve or reject.
Success story sharing