Fetch 和 async await 总是返回 undefined

Fetch and async await always returninig undefined

我的一个服务器调用 return 数据花费了将近 30 秒,所以它总是变得不确定,所以我正在使用异步并承诺解决这个问题但得到 "undefined"。以下是我的代码片在此先感谢

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

正如 peeps 之前在评论中所说,当您希望一个函数为您提供一个值时,您应该为它使用 return 关键字。因此,在这种情况下,您实际上 return 编辑了 fetch 响应,但忘记了 return 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();