我正在尝试学习如何用async和await代替回调函数。两天后,我将进行以下工作,它将从inside function。
中将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)
谢谢,
只需从此行中删除await:
const json = await response.json()
当您使用async关键字时,该功能会自动返回一个Promise。
并且await关键字用于等待承诺解决。
您可以轻松地做到这一点:
$roster = await requestRoster();
但是请注意,这只能在本身是异步的函数中完成。如果要在顶层使用它,可以使用IIFE(立即调用函数表达式),如下所示:
(async () => {
$roster = await requestRoster();
})();