JS - Best Practices (Async Code)

 

Use Promises whenever you can : instead of writing nested callbacks, you can have chainable Promise calls.

Avoid :

asyncFunc1((err, result1) => {
  asyncFunc2(result1, (err, result2) => {  
    asyncFunc3(result2, (err, result3) => {   
      console.lor(result3) })
}) })


Prefer :

asyncFuncPromise1()
.then(asyncFuncPromise2)
.then(asyncFuncPromise3)
.then((result) => console.log(result))
.catch((err) => console.error(err))

 

You can use async/await also :

var foo = async (function() {
var resultA = await (firstAsyncCall());
var resultB = await (secondAsyncCallUsing(resultA));
var resultC = await (thirdAsyncCallUsing(resultB));
       return doSomethingWith(resultC);
});

 
 

js best practices

×