【问题标题】:How to translate Promise code to async await如何将 Promise 代码转换为异步等待
【发布时间】:2018-03-23 17:46:21
【问题描述】:

我在js中有一些简单的Promise:

 let link = "https://jsonplaceholder.typicode.com/posts/1";            
             
 fetch(link)
      .then(response => response.json())  
      .then(data => console.log(data))         
      .catch(error => console.error(error));

...我想把它翻译成'async await',就像这里:

  const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';

  const fetchUsers = async () => {
  const response = await fetch(API_ENDPOINT);
  const data = await response.json();  
  };

...但我不知道如何正确地将其包含在“异步等待”中。这涉及到错误:

fetchUsers()
    .then(response => response.json())
    .then (data => console.log(data))
    .catch(error => console.error(`ERROR ${error}`));

你能帮我解决这个错误吗?

【问题讨论】:

  • 什么错误?
  • 看起来您现在正尝试连续两次呼叫.json()

标签: javascript promise async-await


【解决方案1】:
 const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1';

  const fetchUsers = async () => {
    const response = await fetch(API_ENDPOINT);
    const data = await response.json();  
    console.log(data);
  };

您的代码运行良好只需调用 fetchUsers() 它将通过这一行打印数据console.log(data);

你不能在async类型函数之外使用await关键字

阅读 -

一个异步函数可以包含一个等待表达式来暂停 执行异步函数并等待传递的 Promise 解决,然后恢复异步函数的执行和 返回解析后的值。

请记住,await 关键字仅在异步函数中有效。如果 你在异步函数体之外使用它,你会得到一个 语法错误。

【讨论】:

    【解决方案2】:

    这里有两个问题;

    1. 您不会从异步函数返回任何内容
    2. 您申请response.json() 两次。

    只需将代码更正为;

    const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1',
          fetchUsers   = async () => { var response = await fetch(API_ENDPOINT);
                                       return await response.json();
                                     };
    fetchUsers().then (data => console.log(data))
                .catch(error => console.error(`ERROR ${error}`));
    

    【讨论】:

      【解决方案3】:

      异步函数必须是函数。因此,您需要创建一个函数来执行此操作。 MDN 说:

      async 函数声明定义了一个异步函数,它返回一个 AsyncFunction 对象。

      MDN上阅读更多相关信息

      所以:

      1. 使用 async 关键字创建函数
      2. 使用await关键字在函数内部执行你的fetch调用
      3. 使用 await 关键字围绕任何与 Promise 相关的操作(如果需要)在函数内执行任何其他操作

      以下示例:

      async function doFetch(link) {
          let result = await fetch(link); // this will wait the result to be fetched
          console.log(result); // this will only log the result of the fetch promise after it is resolved
          let json = await result.json();
          console.log(json);
      }
      const link = 'https://jsonplaceholder.typicode.com/posts/1';
      doFetch(link);
      

      另外,请记住,当您使用 await 关键字时,您的异步代码实际上会同步运行,因此,对任何 Promise 的两次连续调用都将同步运行,如下所示:

      async function foo() {
          let bar = await fetch('https://www.google.com');
      
          // the line below will run just _*AFTER*_ the above line is completely resolved
          let baz = await fetch('https://www.facebook.com');
      }
      

      【讨论】:

      • 我猜你的意思是async function foo(),而不是await function foo()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 2021-10-29
      • 2018-07-12
      • 2013-07-01
      • 1970-01-01
      • 2021-05-17
      • 2015-12-13
      相关资源
      最近更新 更多