我已经从此异步/等待功能中成功获取了诺言:
const fetchJSON= (async () => {
const response = await fetch('http://localhost:8081/getJavaMaps')
return await response.json()
})();
现在,我想将结果转换或分配给数组。这就是console.log(fetchJSON)中的结果:
[[PromiseResult]]: Object
One: "Batman"
Three: "Superman"
Two: "Ironman"
但是,当我执行以下操作时: console.log(fetchJSON.One); console.log(fetchJSON.length);
我总是得到:
undefined
我已经尝试过了:
let myarray = Object.entries(fetchJSON);
但是它不会将PromiseResult对象转换为2d数组。
答案 0 :(得分:0)
必须使用await
语句或then
链来解析所有异步函数。您无法在同步代码中获得异步函数的结果。
(async()=>{
const arr= await fetchJSON();
})();
答案 1 :(得分:-1)
您将fetchJSON设置为函数。 因此,返回将不会返回到fetchJSON。您必须这样处理:
let myResult;
fetchJSON()
.then((result) => {
console.log(result);
myResult = result;
})
.catch((error) => {
console.log(error);
});
或
let myResult = async fetchJSON()
.catch((error) => {
console.log(error);
});
console.log(JSON.stringify(myResult));
未处理的承诺已被弃用。不要只是异步/等待!赶上您的错误! 您至少有一个catch块来处理错误。