DEV Community

Jordan promises – async/await vs .then

Jordan Hansen on August 12, 2019

As I’ve stated in a lot of other posts, I’m a big fan of async/await. I think it’s a pretty clean way to manage code your synchronous and asynchron...
Collapse
 
johncarroll profile image
John Carroll • Edited

Async/await is obviously better (in most cases) then .then() style promise handling, but your first example of "Yucky then usage" seems unnecessarily bad. Unless I am missing something, there is no apparent reason for the code to be implemented that way (other than inexperience).

You could argue that one of the benefits of async/await is that it's harder for an inexperienced programmer to use the syntax improperly, but you haven't made that argument.

That same example can be implemented much more cleanly/realistically (while still using .then())

function getThePizza() {
  let someData;

  return functionGettingFromMongo('someArguments')
    .then(data => {
      someData = data;
      return doSomeWorkWithAPromise();
    })
    .then(data => insertToMongoNow(someData + data))
    .then(response => { console.log('success!', response) })
    .catch(e => { console.error('some error happened', e) })
}

While .then() isn’t a callback function, codewise it reads the exact same.

False. It only reads that way because of a poor implementation.

Collapse
 
gypsydave5 profile image
David Wickes

Your example of 'bad' promises would look nicer with a Promise.all (imho), and would incidentally run the two asynchronous calls concurrently.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Async your post is good await the punchline then laugh. Sorry couldn't resist!