【问题标题】:How to console.log the data properly with fetch?如何使用 fetch 正确地控制台记录数据?
【发布时间】:2021-03-24 18:09:05
【问题描述】:

像下面的代码 sn-p 那样返回数据而不是 promise 对象的正确方法是什么?

const getData = async () => {  
  try {
    const res = await fetch(API_ENDPOINT);
    const data = res.json();
    return data; 
  } catch (error) {
    ToastAndroid.show(error, ToastAndroid.LONG);
  }
};
    
console.log(getGeneralData());

【问题讨论】:

  • 因为Body.prototype.json 仍然返回一个Promise,所以无论如何你都需要await res.json()
  • 它仍然返回一个承诺
  • 正如塞巴斯蒂安所说,你需要const data = await res.json();
  • @MikeWazowksi 你的问题是getGeneralData()。你的意思是getData() 吗?无论如何,我认为你在这里别无选择。 .then 只能在 async 函数内部避免(或者如果引擎支持 top-level await 并且 JS 在模块中,则全局避免)。或者,您可以使用(async () => { console.log(await getData()); })();

标签: javascript asynchronous async-await fetch


【解决方案1】:

异步函数返回一个promise,你需要使用:

getData().then(res=>console.log(res);

【讨论】:

  • 但是不使用async和await是为了避免使用then()?
  • 通过使 getData() 异步,您使 getData 异步并允许在其范围内使用“等待”。但是 console.log() 在异步范围之外,你不能使用 await 关键字。但是,如果您的 console.log() 在异步函数中,您可以执行 console.log(await getData());
【解决方案2】:

您可以将代码包装在“自调用”函数(async function() {....})() 中,它允许您使用await 等待getData() 的结果。

(async function() {
  const getData = async() => {
    try {
      const res = await fetch(API_ENDPOINT);
      const data = res.json();
      return data;
    } catch (error) {
      ToastAndroid.show(error, ToastAndroid.LONG);
    }
  };

  console.log(await getData());
})();

【讨论】:

    【解决方案3】:

    async 函数只是 Promise 的语法糖。你可以调用.then()方法来处理promise的解析。

    const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1/comments';
    
    const getData = async () => {
      try {
        const res = await fetch(API_ENDPOINT);
        return res.json();
      } catch (error) {
        ToastAndroid.show(error, ToastAndroid.LONG);
      }
    };
    
    getData().then(data => console.log(data));
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 2019-07-08
      • 2017-01-18
      • 2020-11-06
      相关资源
      最近更新 更多