Javascript 等待/异步功能 - 如果函数中没有等待字怎么办?

2024-03-15

我正在学习 Javascript ES2017 异步/等待功能。 阅读了很多相关内容,并发现等待就像yield一样,允许我们等待承诺完成。

From https://javascript.info/async-await https://javascript.info/async-await

async function showAvatar() {

  // read our JSON
  let response = await fetch('/article/promise-chaining/user.json');
  let user = await response.json();

  // read github user
  let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
  let githubUser = await githubResponse.json();

  // show the avatar
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);

  // wait 3 seconds
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));

  img.remove();

  return githubUser;
}

showAvatar();

我的问题是,我可以在每一行代码中添加await吗? 或者如果我删除“等待”一词会发生什么?

另一个问题是,如果 async/await 使代码看起来同步且按顺序运行,为什么我们根本不使用它(意味着首先让所有内容保持同步?)

谢谢你!


async函数只是 Promise 周围的语法糖。它不会将函数更改为同步。事实上任何函数async隐式返回一个Promise object.

All await所做的是提供一种方便的方法来等待 Promise。如果您删除await关键字,然后Promise不会被“解开”,如果你的函数要对 Promise 的结果进行操作,这不是你想要的。

为了说明这一点,这是异步函数的脱糖版本:

function showAvatar() {

  let githubUser;

  // read our JSON
  return fetch('/article/promise-chaining/user.json').then(response => {
    return response.json();
  }).then(user => {
    // read github user
    return fetch(`https://api.github.com/users/${user.name}`);
  }).then(githubResponse => {
    return githubResponse.json();
  }).then(user => {
    githubUser = user;

    // show the avatar
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);

    // wait 3 seconds
    return new Promise((resolve, reject) => setTimeout(resolve, 3000));
  }).then(() => {
    img.remove();

    return githubUser;
  });
}

So await本质上只是添加一个.then对 Promise 的回调。没有await被指定后,您将只有一个 Promise 对象,而不是 Promise 的结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript 等待/异步功能 - 如果函数中没有等待字怎么办? 的相关文章

随机推荐