返回

JS循环中async、await的正确姿势

前端

概述

在JavaScript循环中,使用asyncawait可以让你编写更易于阅读、更易于维护的代码。 这些关键字允许你在循环中执行异步操作,而不用担心回调函数和Promise。

<h2>循环方式</h2>
<p>
    有四种主要的方法可以在循环中使用<code>async</code><code>await</code>
</p>
<ol>
    <li><strong>for</strong>循环</li>
    <li><strong>map</strong>方法</li>
    <li><strong>forEach</strong>方法</li>
    <li><strong>filter</strong>方法</li>
</ol>

<h3 id="for循环">for循环</h3>
<p>
    你可以通过使用<code>async</code><code>await</code>关键字来创建一个异步的<code>for</code>循环。
    例如,以下代码将创建一个循环,该循环将遍历一个数组,并在每个元素上执行一个异步操作:
</p>

<pre>
    async function asyncForEach(array, callback) {
      for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
      }
    }

    asyncForEach([1, 2, 3], async (element) => {
      // 在这里执行异步操作
    });
</pre>

<h3 id="map方法">map方法</h3>
<p>
    你还可以通过使用<code>async</code><code>await</code>关键字来创建一个异步的<code>map</code>方法。
    例如,以下代码将创建一个循环,该循环将遍历一个数组,并将每个元素上的异步操作的结果存储到一个新数组中:
</p>

<pre>
    const asyncMap = async (array, callback) => {
      const results = [];
      for (let index = 0; index < array.length; index++) {
        results.push(await callback(array[index], index, array));
      }
      return results;
    };

    const result = await asyncMap([1, 2, 3], async (element) => {
      // 在这里执行异步操作
      return element * 2;
    });
</pre>

<h3 id="forEach方法">forEach方法</h3>
<p>
    你还可以通过使用<code>async</code><code>await</code>关键字来创建一个异步的<code>forEach</code>方法。
    例如,以下代码将创建一个循环,该循环将遍历一个数组,并在每个元素上执行一个异步操作:
</p>

<pre>
    const asyncForEach = async (array, callback) => {
      for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
      }
    };

    asyncForEach([1, 2, 3], async (element) => {
      // 在这里执行异步操作
    });
</pre>

<h3 id="filter方法">filter方法</h3>
<p>
    你还可以通过使用<code>async</code><code>await</code>关键字来创建一个异步的<code>filter</code>方法。
    例如,以下代码将创建一个循环,该循环将遍历一个数组,并将满足特定条件的元素过滤到一个新数组中:
</p>

<pre>
    const asyncFilter = async (array, callback) => {
      const results = [];
      for (let index = 0; index < array.length; index++) {
        if (await callback(array[index], index, array)) {
          results.push(array[index]);
        }
      }
      return results;
    };

    const result = await asyncFilter([1, 2, 3], async (element) => {
      // 在这里执行异步操作
      return element > 2;
    });
</pre>

<h2>结论</h2>
<p>
    <code>async</code><code>await</code>关键字是JavaScript中非常强大的工具,它们可以让你编写更易于阅读、更易于维护的代码。
    通过使用这些关键字,你可以在循环中执行异步操作,而不用担心回调函数和Promise。
</p>