1
问题异步函数,该函数不等到地图将完成如何使基于承诺
我认为解决方案是Promise.all 但我不知道如何使用此功能
exports.createProduct = (data) => {
var imgS3arr = []; //array which we waiting for
data.img.map((img, i) => {
fetch.remote(img).then((base) => {
var buf = Buffer.from(base[0], 'base64');
var imgS3 = {
Key: data.title + i, //TODO: add random
Body: buf,
ContentEncoding: 'base64',
ContentType: 'image/jpeg'
};
s3Bucket.putObject(imgS3, function (err, data) {
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
var params = this.request.params;
var region = this.request.httpRequest.region;
imgS3arr.push('https://s3-' + region + '.amazonaws.com/' + params.Bucket + '/' + params.Key)
}
}
);
}).catch((reason) => { });
});
//next part of code must be executed when all items pushed to 'imgS3arr'
const product = new Product({
title: data.title,
img: imgS3arr, //we waiting for this array
});
return product.save((function (err) {
if (err) {
console.log(err);
} else {
console.log('Added new! \n' + product);
}
}));
}
可有一个人帮我这个麻烦?
您混合定期回调和承诺异步。首先要做的就是将这段代码中的所有异步操作转换为promise。然后,用'Promise.all()'等待将是微不足道的。 – jfriend00