Thumb Rules for Using Promises Use promises whenever you are using asynchronous or blocking code. resolve maps to then and reject maps to catch for all practical purposes. Make sure to write both .
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
Yes, you read that right. The V8 team made improvements that make async/await functions run faster than traditional promises in the JavaScript engine.
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.
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.
Full comparison with pros and cons.
Plain JavaScript
- Does not require any additional libraries or technology
- Offers the best performance
- Provides the best level of compatibility with third-party libraries
- Allows the creation of ad hoc and more advanced algorithms
- Might require extra code and relatively complex algorithms
Async (library)
- Simplifies the most common control flow patterns
- Is still a callback-based solution
- Good performance
- Introduces an external dependency
- Might still not be enough for advanced flows
Promises
- Greatly simplifies the most common control flow patterns
- Robust error handling
- Part of the ES2015 specification
- Guarantees deferred invocation of onFulfilled and onRejected
- Requires promisify callback-based APIs
- Introduces a small performance hit
Generators
- Makes non-blocking API look like a blocking one
- Simplifies error handling
- Part of ES2015 specification
- Requires a complementary control flow library
- Still requires callbacks or promises to implement non-sequential flows
- Requires thunkify or promisify nongenerator-based APIs
Async await
- Makes non-blocking API look like blocking
- Clean and intuitive syntax
- Requires Babel or other transpilers and some configuration to be used today
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With