A

Async Await 从初学者到高级功能包括并发 Async Await 教程为什么?

2025-06-10

Async Await 从入门到高级功能(包括并发)

Async Await 教程

为什么?

Async Await 教程


YouTube频道链接:https://www.youtube.com/channel/UC3b871DqOlA5tKbizv4J6mg

什么是 Async Await?

Async await 用于在 JavaScript 中执行异步任务。上面的教程视频介绍了 Async await 和并发。

使用并发编写更好的代码

如果你来这里是为了学习 Async Await,请观看上面的视频。下面我们将演示并发的威力!

这是一个返回 Promise 的等待函数。Promise 会根据传递给它的参数的毫秒数进行解析。

const wait = (ms) => {
    return new Promise(function(resolve) {
        setTimeout(resolve, ms, 'Message Received');
    });
}
Enter fullscreen mode Exit fullscreen mode

下面的 findMessage() 函数将等待对上面 wait() 函数的 3 次异步调用。调用 wait 函数并传入 2000。这意味着该 Promise 将在 2 秒内完成解析。这段代码的执行耗时 6 秒。

const findMessage = async () => {
  const timeStart = Date.now()
  const one = await wait(2000)
  console.log(one)
  const two = await wait(2000)
  console.log(two)
  const three = await wait(2000)
  console.log(three)
  const timeEnd = Date.now()
  console.log(`Time ${timeEnd - timeStart}`)
}

findMessage()
Enter fullscreen mode Exit fullscreen mode

下面的 findMessageConcurrently() 函数将等待对上面 wait() 函数的 3 次异步调用。调用 wait 并传入 2000。这意味着该 Promise 将在 2 秒内完成解析。这段代码的执行时间略长于 2 秒。

const findMessageConcurrently = async () => {
   const timeStart = Date.now()
   const [one, two, three] = await Promise.all([wait(2000),
 wait(2000), wait(2000)])
   console.log(one)
   console.log(two)
   console.log(three)
   const timeEnd = Date.now()
   console.log(`Time ${timeEnd - timeStart}`)
 }

findMessageConcurrently()
Enter fullscreen mode Exit fullscreen mode

为什么?

使用 Promise.all 时,每个传入的 Promise 都会被启动。然后,它会被添加到事件循环的末尾,等待响应。第二个 Promise 的两个 Promise 都可以使用 Promise.all 并发执行。

鏂囩珷鏉ユ簮锛�https://dev.to/papasanto/async-await-from-beginner-to-advanced-features-include-concurrency-16c
PREV
学习 MongoDB:CRUD 基础知识
NEXT
清理 useEffect Hooks 中的异步请求