JavaScript - 异步迭代



异步迭代

在 JavaScript 中,异步迭代指的是迭代异步序列或集合的能力,例如异步函数或生成器返回的那些序列或集合。异步迭代通常与涉及异步任务的操作一起使用,例如从远程服务器获取数据或从文件读取数据。

理解异步操作

简单来说,编程中的异步操作是指在等待完成期间不会阻塞程序执行的任务或过程。这些异步任务使程序能够在等待当前任务完成的同时继续执行其他任务,而不是在继续下一个任务之前暂停等待每个操作完成。

使用 'for await...of' 循环

for await...of 循环用于异步迭代。它的工作方式与常规的 for...of 循环类似,但它设计用于与异步迭代器一起工作。异步迭代器是一个定义了 async next() 方法的对象,该方法返回对序列中下一个值的承诺。

示例:使用 Promise

JavaScript 使用 Promise 来处理异步操作;Promise 代表异步操作的结果(成功或失败)。这里,函数 asyncOperation 模拟这样的操作,返回一个 Promise。for await...of 循环优雅地遍历异步序列,突出了在管理非阻塞操作时使用 Promise 的方式,而不会影响代码的可读性。

<!DOCTYPE html>
<html>
<body>
<h2>Async Iteration with Promises</h2>
<div id="output"></div>
<script>
  function asyncOperation(value) {
    return new Promise(resolve => {
      setTimeout(() => {
        document.getElementById('output').innerHTML += `<p>Processed: ${value}</p>`;
        resolve(value);
      }, 1000);
    });
  }

  const asyncIterable = {
    [Symbol.asyncIterator]: async function* () {
      for (let i = 1; i <= 3; i++) {
        yield await asyncOperation(i);
      }
    },
  };

  async function processAsyncIterable() {
    for await (const result of asyncIterable) {
      document.getElementById('output').innerHTML += `<p>Received: ${result}</p>`;
    }
  }

  processAsyncIterable();
</script>
</body>
</html>

示例 2:使用 Fetch API 进行异步 HTTP 请求

在这里,我们演示了使用 Fetch API 进行 HTTP 请求的异步迭代:asyncIterable 以异步方式获取数据。此外,使用 for await...of 循环优雅地遍历结果,展示了异步迭代与从外部数据源检索数据如何无缝结合。

<!DOCTYPE html>
<html>
<body>
<h2>Async Iteration with Fetch API</h2>
<div id="output"></div>
<script>
  const url = 'https://jsonplaceholder.typicode.com/todos/';
  const asyncIterable = {
    [Symbol.asyncIterator]: async function* () {
      for (let i = 1; i <= 3; i++) {
        const response = await fetch(`${url}${i}`);
        const data = await response.json();
        document.getElementById('output').innerHTML += `<p>Received: ${JSON.stringify(data)}</p>`;
        yield data;
      }
    },
  };

  async function processAsyncIterable() {
    for await (const result of asyncIterable) {
      // Already displaying results above, no need for additional output.
    }
  }

  processAsyncIterable();
</script>
</body>
</html>

示例 3:使用回调函数

这种方法使用基于回调的方法来实现异步迭代。函数 asyncOperation 模拟异步任务并在完成时进行回调。同时,processAsyncIterable 函数积极地遍历数组,为每个元素调用异步操作。

<!DOCTYPE html>
<html>
<body>
<h2>Async Iteration with callback</h2>
<div id="output"></div>
<script>
  function asyncOperation(value, callback) {
    setTimeout(() => {
      document.getElementById('output').innerHTML += `<p>Processed: ${value}</p>`;
      callback(value);
    }, 1000);
  }

  function processAsyncIterable(iterable, callback) {
    const iterator = iterable[Symbol.iterator]();  
    function iterate() {
      const next = iterator.next();
      if (next.done) {        
        return;
      }

      const value = next.value;
      asyncOperation(value, result => {
        document.getElementById('output').innerHTML += `<p>Received: ${result}</p>`;
        iterate(); 
      });
    }
    iterate(); 
  }

  const asyncIterable = [5,6,7,8,9,10]; 
  processAsyncIterable(asyncIterable, result => {
    // You can handle final result or additional actions here if needed.
  });
</script>
</body>
</html>

示例 4:带有错误的 Promise

JavaScript 中的 .then() 方法使用一个或两个回调函数来处理 Promise 的成功解析:如果 promise 解析成功,则执行第一个函数;如果 promise 拒绝,则执行可选的第二个函数。

.catch() 方法用于处理 Promise 的拒绝。当 promise 拒绝时,将执行一个回调函数;这为处理异步操作中的错误提供了一种优雅的解决方案,无需专门用于错误处理的 .then() 块。

<!DOCTYPE html>
<html>
<head>
  <style>
    #output {
      margin-top: 20px;
    }
  </style>
</head>
<body>
<h2>Async Iteration with Promises</h2>
<button onclick="startAsyncIteration()">Start Async Iteration</button>
<div id="output"></div>
<script>
  function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  function fetchData(index) {
    return new Promise((resolve, reject) => {
      if (index < 5) {
        delay(1000).then(() => resolve(`Data ${index}`));
      } else {
        // Simulate an error for index 5
        reject(new Error('Error fetching data for index 5'));
      }
    });
  }

  function startAsyncIteration() {
    document.getElementById('output').innerHTML = '';
    let index = 0;
    function iterate() {
      fetchData(index)
        .then(data => {
          displayData(data);
          index++;
          if (index < 6) {
            iterate();
          }
        })
        .catch(error => {
          // Display error on the page.
          displayError(error.message);
        });
    }
    iterate();
  }

  function displayData(data) {
    const outputDiv = document.getElementById('output');
    outputDiv.innerHTML += `<p>Data received: ${data}</p>`;
  }

  function displayError(errorMessage) {
    const outputDiv = document.getElementById('output');
    outputDiv.innerHTML += `<p style="color: red;">Error: ${errorMessage}</p>`;
  }
</script>
</body>
</html>

现实世界中的用例

在现实世界中,我们使用 JavaScript 异步迭代来优化各种异步操作:在 Web 应用程序中同时从多个 API 获取数据;处理实时更新(对于聊天系统至关重要);执行需要大量资源的批量任务或并行任务;处理文件操作和流;处理交互式 Web 页面上的并发用户交互;处理来自物联网设备的数据;动态加载网页内容;以及离线优先应用程序的数据同步等。

广告
© . All rights reserved.