【发布时间】:2020-02-29 21:58:28
【问题描述】:
我正在尝试学习如何用 async 和 await 替换回调函数。两天后,我进行了以下工作,它将json从函数内部写入控制台。
const requestRoster = async ()=> {
const response = await fetch('/testing/getRoster.php', {
method: 'get',
headers: {
'Content-Type': 'application/json'
}
})
const json = await response.json()
console.log(json); // writes the array json to the console
return json; //apparently returns a pending promise
}
然而,当我说
$roster = requestRoster();
console.log ($roster); // writes Promise{<pending}> to the console
控制台报告
承诺{} 当我展开这条线时,我看到:
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(64)
并且 Array(64) 包含我想要的数据。
显然我在这里有点迷路了。显然,函数 requestRoster() 正在返回一个未决的承诺。 我想要的是它返回 Array(64)。那么,我哪里错了?我只是想让 requestRoster() 返回 Array(64)
谢谢,
【问题讨论】:
-
它不能返回结果,它是异步的。你需要等待承诺。
-
$roster = await requestRoster(); -
谢谢各位大佬,我还有很多要思考和学习的地方
标签: javascript es6-promise fetch-api