从 JavaScript 中的异步函数返回值?
returning values from async functions in JavaScript?
我有以下片段
"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())
请求工作正常,但 console.log() 产生:
{}
200
而不是
200
"it Works!"
当我尝试:
console.log(await doRequest())
我收到 Unexpected Token
错误
async
函数 return 承诺 。在顶层,您必须 "subscribe" 承诺:
doRequest().then(result => console.log(result));
我有以下片段
"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())
请求工作正常,但 console.log() 产生:
{}
200
而不是
200
"it Works!"
当我尝试:
console.log(await doRequest())
我收到 Unexpected Token
错误
async
函数 return 承诺 。在顶层,您必须 "subscribe" 承诺:
doRequest().then(result => console.log(result));