2015-11-11 75 views
1

我有下面的代碼片段從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錯誤

回答

2

async函數返回承諾。在頂層您必須「訂閱」承諾:

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