从javascript提取JSON返回

我正在尝试学习如何用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)

谢谢

heiheie 回答:从javascript提取JSON返回

使用async关键字时,该函数会自动返回一个Promise

await关键字用于等待承诺解决。

您可以轻松地做到这一点:

$roster = await requestRoster();

但是请注意,这只能在async本身的函数中完成。如果您想在顶层使用它,可以使用IIFE(立即调用函数表达式),如下所示:

(async () => {
  $roster = await requestRoster();
  // do something with $roster here
})();
,

即使您返回一个简单值,一个声明的async函数也会返回一个promise。如果返回这样的值,它将被包装到一个已经解析的Promise中,您可以读出已知的方式。

如果您正在使用另一个异步功能,则可以等待它。

$roster = await requestRoster();

在简单的函数或箭头函数中,可以使用promise方法。

requestRooster().then( (roster) => { /* do something with rooster*/ } );
,

只需从此行中删除等待

const json = await response.json()
本文链接:https://www.f2er.com/3165825.html

大家都在问