如何将Promise代码转换为异步等待 [英] How to translate Promise code to async await

查看:40
本文介绍了如何将Promise代码转换为异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some simple Promise in js:

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

...,我想将其翻译为异步等待",如下所示:

... and I want to translate it to 'async await' like here:

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

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

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

... but I don't know how involve it in 'async await' correctly. This involving gives error:

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

您能帮我解决此错误吗?

Can you help me fix this error?

推荐答案

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

Async functions must be functions. So, you need to create a function to do that. MDN says:

异步函数声明定义了一个异步函数,该函数返回一个AsyncFunction对象.

The async function declaration defines an asynchronous function, which returns an AsyncFunction object.

MDN 上了解有关此内容的更多信息>

Read more about that on MDN

所以:

  1. 使用async关键字创建函数
  2. 使用await关键字在内部执行fetch调用
  3. 使用await关键字围绕任何与Promise相关的操作(如果需要)执行功能内的任何其他操作
  1. Create a function using the async keyword
  2. Perform your fetch call inside the function using the await keyword
  3. Perform any other operations inside your function using the await keyword around any promise related operations (if you want)

以下示例:

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的两个顺序调用将同步运行,如下所示:

Also, remember that when you use the await keyword, your asynchronous code will actually run synchronously, so, two sequential calls to any promises will run synchronously, like so:

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');
}

这篇关于如何将Promise代码转换为异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆