javascript - 如何优雅的执行 forEach 中异步方法的完成回调
本文介绍了javascript - 如何优雅的执行 forEach 中异步方法的完成回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
功能需求
根据标签列表循环下载对应图片
现有代码
var imageFiles = [];
data.imageTags.forEach((item, index, array) => {
wx.downloadFile({
url: `${ $http.baseURL }yun/image/${ item }`,
header: $http.baseHeader,
success: res => {
imageFiles[index] = res.tempFilePath;
index == array.length - 1 && that.setData({ 'data.imageFiles': imageFiles });
}
});
});
存在问题
部分图片过大时 imageFiles
对应为 null
请问该如果解决(不太想 var i=0;
回调成功 i++
这种做法
解决方案
楼上都只是摆了个 Promise 架子,思路还是一样,并没有解决到实际问题呢。
题主其中一个重要问题是默认最后一个回调是最后到达的,index == array.length - 1 && ...
这个假设明显不成立。
题主应该是需要一个不会 fail 的 Promise.all,也就是 reflect,有的库提供,没有可以自行封装一个。
供参考
function downloadFile (tag) {
return new Promise((resolve, reject) => {
wx.downloadFile({
url: `${ $http.baseURL }yun/image/${ tag }`,
header: $http.baseHeader,
success: res => resolve(res.tempFilePath)
});
})
}
function promiseReflect (iterable) {
if (!Array.isArray(iterable)) {
iterable = Array.from(iterable);
}
return Promise.all(iterable.map(p => typeof p.catch === 'function' ? p.catch(() => null) : p));
}
promiseReflect(imageTags.map(tag => downloadFile(tag)))
.then(imageFiles => {
// 可以 filter 掉失败的图片
that.setData({ 'data.imageFiles': imageFiles });
})
这篇关于javascript - 如何优雅的执行 forEach 中异步方法的完成回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文