Bluebird .map 承诺提前结束?
Bluebird .map promise ends prematurely?
我 运行 在我的承诺代码中遇到了一些麻烦,我的 Promise.map 似乎过早结束了。我确定这是我的逻辑问题,但我不确定如何调试代码。
目前,它输出 [], B, A, A
,blobList
大小为 2。我怎样才能让它完成推送到 imgList
,从而输出 A, A, [*some base64 encoding here*], B
,其中在.then
函数中,imgList不应该为空?
blobToBase64 函数
blobToBase64(blob, cb) {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
let base64data = reader.result;
cb(base64data);
}
}
主要功能
Promise.map(blobList, function(blobObj){
helper.blobToBase64(blobObj.data, (fn) => {
imgList.push(fn);
console.log('A');
})
}).then(function(){
console.log(imgList);
console.log('B');
})
给你:
var promises = blobList.map((blobObj) => {
return new Promise((resolve, reject) => {
helper.blobToBase64(blobObj.data, (fn) => {
imgList.push(fn);
console.log('A');
return resolve();
})
})
})
Promise
.all(promises)
.then(() => {
console.log(imgList);
console.log('B');
})
我 运行 在我的承诺代码中遇到了一些麻烦,我的 Promise.map 似乎过早结束了。我确定这是我的逻辑问题,但我不确定如何调试代码。
目前,它输出 [], B, A, A
,blobList
大小为 2。我怎样才能让它完成推送到 imgList
,从而输出 A, A, [*some base64 encoding here*], B
,其中在.then
函数中,imgList不应该为空?
blobToBase64 函数
blobToBase64(blob, cb) {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
let base64data = reader.result;
cb(base64data);
}
}
主要功能
Promise.map(blobList, function(blobObj){
helper.blobToBase64(blobObj.data, (fn) => {
imgList.push(fn);
console.log('A');
})
}).then(function(){
console.log(imgList);
console.log('B');
})
给你:
var promises = blobList.map((blobObj) => {
return new Promise((resolve, reject) => {
helper.blobToBase64(blobObj.data, (fn) => {
imgList.push(fn);
console.log('A');
return resolve();
})
})
})
Promise
.all(promises)
.then(() => {
console.log(imgList);
console.log('B');
})