我对node.js和javascript一般都比较新。特别是,我对promises和async / await感到困惑。我试图从远程URL异步请求图像并将它们转换为base64。 有人可以解释下面我的代码有什么问题吗?
function loadAsync(image){
return new Promise(function(resolve,reject){
request({url: image, encoding: null}, function (err, res, body) {
if (!err && res.statusCode == 200) {
let base64prefix = 'data:' + res.headers['content-type'] + ';base64,'
let image = body.toString('base64');
let complete = base64prefix + image;
resolve(complete)
} else {
return reject(err);
}
});
});
}
async function getImagesAsBase64(images){
let promises = [];
images.forEach(image =>{
promises.push(loadAsync(image).then(results =>{
return results;
}));
});
const imagesAsBase64 = await Promise.all(promises);
return imagesAsBase64;
}
//Following returns Promise{<pending>} when given an array of images
console.log(getImagesAsBase64(images));
答案 0 :(得分:2)
愚蠢的我,我需要await
结果
let imagesAsBase64 = await getImagesAsBase64(images);
console.log(imagesAsBase64);