链式调用异步函数

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探索如何在 JavaScript 中链式调用异步函数。我们将学习如何遍历包含异步事件的函数数组,并在每个事件完成时调用 next 函数。在实验结束时,你将能够以特定顺序高效地执行一系列异步操作。

链式调用异步函数

要链式调用异步函数,请打开终端/SSH 并输入 node。然后,遍历包含异步事件的函数数组,并在每个异步事件完成时调用 next 函数。

以下是一个演示如何链式调用异步函数的代码片段:

const chainAsync = (fns) => {
  let curr = 0;
  const last = fns[fns.length - 1];
  const next = () => {
    const fn = fns[curr++];
    fn === last ? fn() : fn(next);
  };
  next();
};

chainAsync([
  (next) => {
    console.log("0 秒");
    setTimeout(next, 1000);
  },
  (next) => {
    console.log("1 秒");
    setTimeout(next, 1000);
  },
  () => {
    console.log("2 秒");
  }
]);

总结

恭喜你!你已经完成了“链式调用异步函数”实验。你可以在 LabEx 中练习更多实验来提升你的技能。