[英]Return 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 一起使用
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 }
但是如果我在gh
上放了一個 console.log,我就從請求中得到了值,但我不希望githubActivity()
記錄我想要返回的值。
我也試過這個:
async function githubActivity () {
return await reqGitActivity(`https://api.github.com/users/${github}/events`)
.then(function (res) {
return res
})
}
但我仍然只得到 Promise 而不是解析的值。
有什么想法嗎?
看來您只能在回調內部訪問該值 。
因此,代替使用console.log(JSON.parse(githubActivity()))
,請使用:
githubActivity().then( body => console.log( JSON.parse( body ) ) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.