我已成功从此 async/await 函数中检索到承诺:
const fetchJSON= (async () => {
const response = await fetch('http://localhost:8081/getJavaMaps')
return await response.json()
})();
Run Code Online (Sandbox Code Playgroud)
现在我想将结果转换或分配给数组。这就是 console.log(fetchJSON) 中的结果:
[[PromiseResult]]: Object
One: "Batman"
Three: "Superman"
Two: "Ironman"
Run Code Online (Sandbox Code Playgroud)
但是,当我执行如下操作时: console.log(fetchJSON.One); console.log(fetchJSON.length);
我总是得到:
undefined
Run Code Online (Sandbox Code Playgroud)
我试过这个:
let myarray = Object.entries(fetchJSON);
Run Code Online (Sandbox Code Playgroud)
但它不会将 PromiseResult 对象转换为二维数组。
所有异步函数都必须使用await
语句或then
链来解析。您无法在同步代码中获取异步函数的结果。
(async()=>{
const arr= await fetchJSON();
})();
Run Code Online (Sandbox Code Playgroud)