【问题标题】:Fetch and async await always returninig undefined获取和异步等待总是返回未定义
【发布时间】:2020-05-11 17:52:45
【问题描述】:

我的一个服务器调用花了将近 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();

【问题讨论】:

  • 你需要返回 fetch
  • fetchFunc() 不返回任何内容

标签: javascript async-await es6-promise


【解决方案1】:

正如 peeps 之前在 cmets 中所说,当您希望函数为您提供值时,您应该使用 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();

【讨论】:

  • 感谢您的帮助我没有注意到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2022-11-06
  • 2021-04-20
  • 2018-03-12
相关资源
最近更新 更多