Search code examples
asynchronousasync-awaites6-promiseecmascript-5

async/await / assignments from function returns


Currently having a simple funtion :

async function getItem(id) {
  const item = await ... doing a bunch of time consuming stuff
  return item;
}

Coming from synchronous languages, and still understanding async/awaits from the surface; i'd expected the following to return the resolved item :

const item = getItem('items-8');
console.log(item); // Just getting a promise

The question is a bit 'cosmetic', but as async/await kind of solves callbacks, i'd be looking to get further and even avoid thenables things.

Is it possible to get such one-liner variable assignment with async/awaits ? What would be the syntax/code structure ?


Solution

  • async..await is syntactic sugar for ES6 promises, it allows to write asynchronous code in synchrounous-like manner. The code that uses promises cannot be synchronous, because promises are asynchronous.

    In order to be written in synchronous manner, the code that uses getItem should reside in async function, too. If it is top-level and doesn't reside in another function (like application initialization code), it can reside in async IIFE.

    It's either

    getItem('items-8').then(item => {
      ...
    });
    

    Or

    // inside `async` function
    const item = await getItem('items-8');
    ...