寫一個簡化的代碼const ids = [1, 2, 3]const resArr = []// 1ids.forEach(id => api(id).then(res => resArr.push(res))// 2Promise.all(ids.map(id => api(id).then(res => resArr.push(res))))api 是使用來發(fā)送 http 請求的一個方法,里面會把 id 拼接到一個特定的地址后面,返回值是一個 promise,請求到數(shù)據(jù)之后在 then 里面把結(jié)果寫入到 resArr。我本來的想法是用 forEach 實(shí)現(xiàn)并發(fā)請求,也就是方法1,但是后來用 Promise.all 寫了一個,也就是方法2,我不知道這兩種方法哪種更好,或者,在性能上有什么差別,按我的理解看起來沒有什么區(qū)別,而且每一次 http 請求我都不需要關(guān)心成功與否,也就是說失敗是可以接受的,所以 Promise.all 雖然會在全部成功或者某一個失敗的時候通知我,但是我不需要關(guān)心這些
關(guān)于 js 并發(fā)請求數(shù)據(jù)的問題
慕運(yùn)維8079593
2019-02-05 19:51:01