The asynchronous method in the JS Array.map method cannot be executed synchronously

1. The asynchronous method in the JS Array.map method cannot be executed synchronously

Question: I send requests in a loop, and there are two photo addresses returned to me in the background. I need to use map to operate on each value, which involves asynchronous operations.
insert image description here
insert image description here

Online example (using promise.all): let arr1 = [1,2,3,4,5] let res = await Promise.all(arr.map(async (item) => { await new Promise(resolve=>{ setTimeout(() => { console.log(item + '内结束'); resolve(); }, 2000) }) return 10 })); console.log(res)

Finally realized:
insert image description here
The principle of the map function is:

循环数组,获取每项数组对应的内容,
调用map函数传入的方法,
获取数组的新内容,
将新内容push到新数组,最后返回。
map函数是同步执行的,所以循环每一项时,到给新数组值时,都是同步操作。

Guess you like

Origin blog.csdn.net/weixin_46319117/article/details/116272770