Async await

Posted on Updated on

Async await

Async/await has come up a lot recently on twitter, coding videos, and blogs. But what is it? Seems like it would be used for callbacks or promises. How something is declared as a async function is that we place async before the function definition. “The word “async” before a function means the function will return a promise.. And if the return value is not a promise, the return is converted to a resolved promise automatically.

function cool(){
  return "cool"
}
console.log(cool());
//cool

async function cool2(){
  return "cool2"
}
console.log(cool2());
//SyntaxError: Unexpected token function

Hmm why did we get an unexpected token function? As the async function is returning a promise, we cant log it, so lets do something else.

cool2().then(a=>{console.log(a)}) 
//now we get the output of “cool2” 
//but we get Promise {<resolved>: undefined}

If we call an empty then, we can see the resolved promise wrapper that is returned.

cool2().then() //Promise {<resolved>: "cool2"}

So now we are seeing that we do get everything wrapped in a promise, even if the return isn’t a promise. To wrap it up we would need to use await. “The await operator is used to wait for a Promise. It can only be used inside an async function.” [MDN] The syntax is returnvalue = await expression,

async function cool3(){
  let rv = await "cool3"
  return rv
}
console.log(cool3()); // we get a pending promise
cool3(); // we get a resolved  promise 
// Promise {<resolved>: "cool3"}

 

What good is this? What would we use it for? Well it appears async await is syntactic sugar for promises, so it’s supposed to make promises look cleaner. The code below is what babel generated from cool3(). Wow, Ill take async/await.

//GENERATED FROM BABEL:
var cool3 = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var rv;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return "cool3";

          case 2:
            rv = _context.sent;
            return _context.abrupt("return", rv);

          case 4:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function cool3() {
    return _ref.apply(this, arguments);
  };
}();

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s