This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Promises: async/await vs .then(), how we got here and why I use both




How we acquired right here

Guarantees marked an enormous turning level in async js, they enabled a brand new kind of management circulation that saved us from callback hell. However some individuals discovered that calling .then() a number of instances was an excessive amount of, too callbacky.

Then after some time, we resorted to generator functions and cogenerators, which made async code really feel like its synchronous, at the price of wrapping it in a generator perform, yielding each line and introducing a cogenerator library (for instance co) to take care of unwrapping the guarantees like the next instance, the place we might simply yield a promise at any time when we encounter it and fake that the yield doesn’t exist on that line of code.

co(perform* () {
  let result1 = yield somePromise1
  let result1 = yield anotherPromise
  dostuff(result1, result2)
})
Enter fullscreen mode

Exit fullscreen mode

This evolution served because the inspiration of the async/await syntax launched in es7, and eventually we might simply

let worth = await somePromise
doStuff(worth)
// as a substitute of
somePromise.then(worth => doStuff(worth)
Enter fullscreen mode

Exit fullscreen mode

Oh, and also you needed to wrap it in an async function to have the ability to use it, however that is altering with high stage await.



Why I take advantage of each

One easy motive: error dealing with.

Writing code for the completely happy path feels good, if solely the world have been an ideal place. However hélas, in the event you omit error dealing with throughout improvement, you’ll pay for it later whereas digging via a mysterious bug report.

Guarantees have a .catch(callback) methodology much like .then(callback) the place the callback expects an error.

myPromise
    .then(worth => handleHappyPath(worth))
    .then(value2 => handleAnotherHappyPath(value2))
    .catch(err => handleError(err))
Enter fullscreen mode

Exit fullscreen mode

The async/await model appears like this:

attempt {
    let worth = await myPromise
    let value2 = await handleHappyPath(worth)
   handleAnotherHappyPath(value2)
} catch(err) {
    handleError(err)
}
Enter fullscreen mode

Exit fullscreen mode

One least used – however very helpful – function of .then is that it accepts a second parameter as an error handler.

myPromise
    .then(handleHappyPath, handleErrorScoped)
    .then(anotherHappyPath)
    .catch(err => handleError(err))
Enter fullscreen mode

Exit fullscreen mode

On this instance, handleErrorScoped will care for errors for this explicit step. Whereas handleError will deal with errors of the entire chain (together with errors inside handleErrorScoped).

The equal sync/await model requires a nested attempt/catch block.

attempt {
    let worth
    attempt {
        worth = await myPromise
    } catch (err) {
        // probably setting `worth` to one thing
        handleErrorScoped(err)
    }
    let value2 = await handleHappyPath(worth)
   handleAnotherHappyPath(value2)
} catch(err) {
    handleError(err)
}
Enter fullscreen mode

Exit fullscreen mode

Possibly it is simply me, however I discover the latter a hell of lot extra verbose, working away from callback hell, ran immediately into attempt/catch hell.

An instance of an occasion the place I discovered myself combining each is once I use puppeteer to test if a component exists in a web page.

let hasElement = await web page.consider(() => doc.querySelector("some selector"))
    .then(() => true)
    .catch(() => false)
Enter fullscreen mode

Exit fullscreen mode



Conclusion

async/await was an enormous stepping stone in direction of simplifying async javascript, however it doesn’t out of date .then() and .catch(), each have their use circumstances, particularly when
we want granular management over error dealing with.

A mixture of each appears to offer essentially the most readable code, sturdy and maintainable code.

Should you made it this far, please present your assist with reactions and do not hesitate to
ask query inside feedback, I might like to reply every one in all them and know your ideas in regards to the dichotomy of async/await vs .then() 🙂

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?