我正在尝试学习如何用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()返回了待处理的Promise。 我想要的是它返回Array(64)。那么,我哪里出问题了?我只希望requestRoster()返回Array(64)
谢谢