从异步函数返回值

编程入门 行业动态 更新时间:2024-10-13 06:13:11
本文介绍了从异步函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从异步函数返回值?

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 ) ) )

更多推荐

从异步函数返回值

本文发布于:2023-11-26 02:27:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632284.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!