如何将PromiseResult对象转换为数组?

6

我已经成功从这个异步/等待函数中检索到一个Promise:

  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对象转换为二维数组。

1
你需要等待 Promise 对象。 - dwjohnston
2个回答

3

所有异步函数必须使用await语句或then链来解决。您无法在同步代码中获取异步函数的结果。

(async()=>{
   const arr= await fetchJSON();
})();

我知道这已经过时了,但是应该将其标记为正确答案。 - spetz83

-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));

未处理的 Promise 已经被弃用。不要只是使用 async/await!一定要捕获错误!

你至少需要一个 catch 块来处理错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接