ES7 Async Functions

node v0.12.18
version: 1.0.0
endpointsharetweet
Async functions are a much easier way to create asynchronous code that has the benefits of promises, but maintains the structure of your old synchronous code. Instead of attaching .then and .catch methods, you can you can use normal semantics and try/catch statements:
var delay = require("bluebird").Promise.delay; function oldPromiseStyleFunction() { return delay(1000) .then(function() { console.log("One Second Passed!"); }) .then(delay(2000)) .then(function() { console.log("Two Seconds Passed!"); }) .catch(function() { console.log("An Error occured!"); }) } async function newAsyncFunction() { try { await delay(1000); console.log("One Second Passed!"); await delay(2000); console.log("Two Seconds Passed!"); } catch (anException) { console.log("An Error occured!"); } } await newAsyncFunction()
These two functions actually behave the same way.
Loading…

4 comments

  • posted 5 years ago by carusog
    Hi, thanks for sharing. There is an error in the promise version. On line 10 you need return a promise to be able to concatenate them. Right now both console logs are executed in parallel. Have a look at https://runkit.com/carusog/es7-async-functions-vs-promises
  • posted 4 years ago by therbendo
    500k?
  • posted 2 years ago by rdvnplt027
    500k
  • posted 2 years ago by rdvnplt027
    Two Seconds Passed

sign in to comment