本文介绍了从异步函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从异步函数返回值?
How can I return the value from an async function?
我有以下承诺:
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) }) }) }然后我将这个Promise与Async/Await一起使用
Then I use this Promise with Async/Await
async function githubActivity () { const gh = await reqGitActivity(`api.github/users/${github}/events`) return gh }如果我执行以下功能:
console.log(JSON.parse(githubActivity()))我仅收到Promise,但没有收到请求返回的值.
I only get the Promise but not the value returned from the request.
Promise { _c: [], _a: undefined, _s: 0, _d: false, _v: undefined, _h: 0, _n: false }但是,如果将console.log放在gh上,我从请求中获取了值,但是我不想githubActivity()记录要返回值的值.
But if I put a console.log on the gh I got the value from the request, but I don't want githubActivity() to log the value I want to return the value.
我也尝试过:
async function githubActivity () { return await reqGitActivity(`api.github/users/${github}/events`) .then(function (res) { return res }) }但是我仍然只能获得Promise,而不能从决心中获得价值.
But I still only get the Promise and not the value from the resolve.
有什么想法吗?
推荐答案您似乎只能在回调内部访问该值.
因此,使用
代替console.log(JSON.parse(githubActivity())):
githubActivity().then( body => console.log( JSON.parse( body ) ) )更多推荐
从异步函数返回值
发布评论