Async/await 仍然会给你带来很多惊喜!

2025-06-08

Async/await 仍然会给你带来很多惊喜!

我热爱科技❤,而且无论我们知道多少,总有一些东西会让我们惊喜。今天我的一个朋友(@Rafael_Toscano)给我看了一些东西,我的第一反应是这样的:

猫很惊讶

他与我分享了一篇来自 V8 博客的关于“更快的异步函数和承诺”的文章。在各种令人兴奋的事情中,有一件事引起了我的注意,我只能想“这不可能是真的,我必须测试一下”。

它涉及 async/await 的行为,以及您可以将 async/await 与任何“thenable”函数一起使用的事实。这是什么意思?任何具有“.then”方法的对象都可以与 async/await 一起使用。

在文章中,他给出了以下例子:

class Sleep {
  constructor(timeout) {
    this.timeout = timeout;
  }
  then(resolve, reject) {
    const startTime = Date.now();
    setTimeout(() => resolve(Date.now() - startTime),
               this.timeout);
  }
}

(async () => {
  const actualTime = await new Sleep(1000);
  console.log(actualTime);
})();
Enter fullscreen mode Exit fullscreen mode

圣母

是的,请告诉我,我不是唯一一个看到这一幕而震惊的人。

我认为这能帮助我们更好地理解 async/await 函数以及我们在代码中可以实现的各种功能。但这也伴随着巨大的责任,请不要仅仅因为感觉好就用它取代所有简单的 Promise。

仅在您能找到特殊用例的情况下才使用它,如果有的话,请在评论中与我们分享。我很乐意听到您的分享!我正在考虑,如果按照下面代码中的想法来实现“重试策略”,这是否是一个不错的选择。

const ServerMock = {
  count: 0,
  getData() {
    if (this.count === 2) {
      return Promise.resolve([{ name: "SomeName" }]);
    } else {
      this.count++;
      return Promise.reject("Error");
    }
  }
};

function fetchData(limit, time) {
  return {
    then(resolve, reject) {
      const retry = setInterval(async () => {
        limit--;
        try {
          console.log("Trying....");
          const data = await ServerMock.getData();
          if (data) {
            console.log("Resolve");
            clearInterval(retry);
            resolve(data);
          }
        } catch {
          if (limit === 0) {
            clearInterval(retry);
            reject("Limit Reached");
          }
        }
      }, time);
    }
  };
}

(async () => {
  try {
    const result = await fetchData(3, 1000);
    console.log(result);
  } catch (err) {
    console.log(err);
  }
})();
Enter fullscreen mode Exit fullscreen mode

请在评论中告诉我你的想法。

鏂囩珷鏉ユ簮锛�https://dev.to/assuncaocharles/async-await-can-still-surprise-you-a-lot-1ebg
PREV
构建并发布您的第一个 NPM 包
NEXT
为什么您首选的编程语言是?