# forEach

function forEach (arr, fn) {
  return new Promise(resolve => {
    next(arr)
    function next (arr, i = 0) {
      const item = arr[i]
      const res = fn(item)

      if (Object.prototype.toString.call(res) === '[object Promise]') {
        res.then(r => {
          arr[i] = r

          if (i === arr.length - 1) {
            resolve(arr)
            return
          }

          next(arr, i + 1)
        })
      } else {
        arr[i] = res

        if (i === arr.length - 1) {
          resolve(arr)
          return
        }

        next(arr, i + 1)
      }
    }
  })
}


const arr = [1, 2, 3]
const p = function Pro (item) {
  return item * 3
  // return new Promise(resolve => {
  //   setTimeout(() => {
  //     resolve(item * 2)
  //   }, 1000);
  // })
}
forEach(arr, p).then(res => {
  console.log(res);
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Last Updated: 6/27/2023, 7:40:45 PM