2016-05-06 121 views
2

如何从异步函数返回值?来自异步函数的返回值

我有如下承诺:

function reqGitActivity (url) { 
    const options = { 
    url: url, 
    headers: { 
     'User-Agent': 'request' 
    } 
    } 

    return new Promise((resolve, reject) => { 
    request(options, (err, res, body) => { 
     if (err) { 
     reject(err) 
     return 
     } 
     resolve(body) 
    }) 
    }) 
} 

然后我用这个承诺与异步/等待

async function githubActivity() { 
    const gh = await reqGitActivity(`https://api.github.com/users/${github}/events`) 
    return gh 
} 

如果我执行的函数:

console.log(JSON.parse(githubActivity())) 

我只能得到Promise,而不能获得请求返回的值。

Promise { 
    _c: [], 
    _a: undefined, 
    _s: 0, 
    _d: false, 
    _v: undefined, 
    _h: 0, 
    _n: false } 

但是,如果我把一个的console.log在gh我从请求的价值,但我不想githubActivity()登录我想返回值的值。

我想这太:

async function githubActivity() { 
    return await reqGitActivity(`https://api.github.com/users/${github}/events`) 
    .then(function (res) { 
     return res 
    }) 
} 

但我仍然只得到了承诺,而不是从解决价值。

有什么想法?

+0

你尝试过使用var GH = ...而不是常量GH = ...? –

+0

@TudorConstantin是的,我仍然得到了诺言。 – Rog

+0

这很疯狂 - 如果你把console.log(gh);在返回gh之前,内容显示为 –

回答

2

它看起来像你只能access that value inside of a callback

所以,与其console.log(JSON.parse(githubActivity())),用途:

githubActivity().then(body => console.log(JSON.parse(body))) 
+1

哦,我明白了!谢谢!我也在阅读:http://stackoverflow.com/questions/35302431/async-await-implicitly-returns-promise – Rog