DEV Community

Discussion on: Asynchronous Programming in Javascript

Collapse
 
savagepixie profile image
SavagePixie • Edited

I think you could do better with your last example on promises. As it is now, it looks like you're pretending that awkwardly written code is how promises are supposed to be written in order to use that as an argument for async/await's superiority.

This code:

promise1
  .then(function(data1){console.log(data1); return new promise2 })
  .then(function(data2){console.log(data2); })
  .catch(function(error){console.log(error);//error caught from any of the promises})

Can be simply rewritten like this:

promise1
   .then(console.log)
   .catch(console.log)
promise2
   .then(console.log)
   .catch(console.log)

If they are separate concerns and do separate things, there is no reason to put them in the same chain. Now, if you need to rely on what the transformed data of promise1 to then do some other asynchronous thing, then itself returns a promise, so you can simply do:

promise1
   .then(transformData)
   .then(anotherAsynchronousCall)
   .catch(error => /* deal with your error */)

I mean, it's perfectly fine if you prefer async/await, I don't mean to dissuade you from using it, but if you want to compare it to promises, at least use a good example of promises.

To compare how clean they look, you could use your last example of async/await and this code here that does the exact same thing with promises:

someAsyncCall()
   .then(function(result) {
      console.log('result', result)
      return 'successful'
   })
   .catch(function(error) {
      console.log(error)
      return 'failed'
   })
   .then(console.log)

Which one looks cleaner? Some people will prefer the one, others will prefer the other. The important thing is that now at least they both look like reasonably clean examples of the same thing done using different approaches, rather than contrived examples that have been purposely crafted to prove a point.

Collapse
 
reddyaravind178 profile image
aravind_reddy • Edited

Thanks for your feedback I have edited and used the same example to compare promise and async-await. actually I want to use the data of the first promise to do another async call. I forgot to mention the details. and I don't want to persuade others to use just the async-await every time it's totally up to what they prefer.. am just presenting all the options and how they evolved.