如何从异步函数返回值?来自异步函数的返回值
我有如下承诺:
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
})
}
但我仍然只得到了承诺,而不是从解决价值。
有什么想法?
你尝试过使用var GH = ...而不是常量GH = ...? –
@TudorConstantin是的,我仍然得到了诺言。 – Rog
这很疯狂 - 如果你把console.log(gh);在返回gh之前,内容显示为 –