29
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Array.fromAsync()とPromise.all()の違い【JavaScript】

Last updated at Posted at 2024-09-18

ようわからんかったのでメモ

TL;DR

  • Array.fromAsync()は順次実行
  • Promise.all()は同時実行
const sleep = delay => new Promise(resolve => setTimeout(resolve, delay))

console.time()
await Array.fromAsync([200, 100, 300], sleep)
console.timeEnd()
// elapsed: 600ms

console.time()
await Promise.all([200, 100, 300].map(sleep))
console.timeEnd()
// elapsed: 300ms

cc @juner

戻り値

どちらも解決した値が入ってくる。HTTPリクエストを投げたいときにDoS攻撃したくないなら、Array.fromAsync()はあり!

const sleep = delay => new Promise(resolve => setTimeout(() => resolve(delay), delay))

console.time()
console.log(await Array.fromAsync([200, 100, 300], sleep))
console.timeEnd()
// elapsed: 600ms

console.time()
console.log(await Promise.all([200, 100, 300].map(sleep)))
console.timeEnd()
// elapsed: 300ms

image.png

こんな感じでDoS攻撃を防げます

const responses = await Array.fromAsync(Array(30), () => fetch('https://httpbin.org/uuid'))
console.log(responses)
29
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?