Search code examples
javascriptasync-awaitbabeljsecmascript-2016

returning values from async functions in JavaScript?


I have the following snippet

"use strict"

const req = require('requisition');

async function doRequest () {
  const url = 'http://api.com/v3/search?q=breno'
  const res = await req.get(url)

  console.log(res.status)

  const body = await res.json();

  return "it Works!"
}


console.log(doRequest())

the requests are working just fine, but the console.log() produces:

{}
200

instead of

200
"it Works!"

when I try to:

console.log(await doRequest())

i get an Unexpected Token error


Solution

  • async functions return promises. At the top level you have to "subscribe" to the promise:

    doRequest().then(result => console.log(result));