1

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 ?

Ben
  • 5,030
  • 6
  • 53
  • 94
  • Possible duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call . It covers all sorts of things, including promises and async/await. – Estus Flask Jan 02 '18 at 11:17
  • @estus If we stick to the titles of the main answer, we have The `"ES2017+: Promises with async/await"` and `"ES2015+: Promises with then()"`. Let me be a but puzzled by the fact that the `ES2017` part ends up with `"then"`; it should then be advertised as `"ES2017+ with still a little bit of ES2015: Promises with async/await/THEN"`. This is more or less why i'm asking there, wondering if a one-liner pattern could be used – Ben Jan 02 '18 at 11:29

1 Answers1

1

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');
...
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • I start to get it, it can't happen outside the async right ? I was puzzled as, for example `async function returnValue(id) { let item = await getItem(id); return item }); let it = returnValue("items-8")` will still return a promise – Ben Jan 02 '18 at 11:41
  • 1
    Yes, it will return a promise indeed. And yes, we need to call `async` functions inside `async` functions in order to keep the code sync-like with no `then`s. – Estus Flask Jan 02 '18 at 11:43