获取并异步等待总是返回未定义状态

问题描述 投票:0回答:1

我的一个服务器调用花费了将近30秒钟来返回数据,因此它总是变得不确定,因此我正在使用异步并承诺解决此问题,但会出现“不确定”的情况。以下是我的代码段预先感谢

   function fetchFunc() {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then((json) => {
                // console.log(json)
                return json;
            })
    }

    function resolveAfter2Seconds() {
        return new Promise(resolve => {
                resolve(fetchFunc());
        });
    }

    async function asyncFunc() {
        debugger
        console.log("res" + resolveAfter2Seconds())
        let response = await resolveAfter2Seconds();
        console.log("response = " + response);
    }
    asyncFunc();
javascript async-await es6-promise
1个回答
1
投票

正如在前面的注视中说的,当您期望一个函数可以为您提供一个值时,您应该使用return关键字。因此,在这种情况下,您实际上返回了fetch响应,但是忘记了返回fetch承诺值本身。

所以您的代码应如下所示:

function fetchFunc() {
  return fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then((json) => {
      // console.log(json)
      return json;
    })
}

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    resolve(fetchFunc());
  });
}

async function asyncFunc() {
  debugger
  console.log("res" + resolveAfter2Seconds())
  let response = await resolveAfter2Seconds();
  console.log("response = " + response);
}
asyncFunc();
© www.soinside.com 2019 - 2024. All rights reserved.