作者:GIfi炬辉_904 | 来源:互联网 | 2023-07-31 14:55
我正在映射数组,并且对于新对象的返回值之一,我需要进行异步调用.varfirebaseDatateachers.map(function(teacher){return{name:
我正在映射数组,并且对于新对象的返回值之一,我需要进行异步调用.
var firebaseData = teachers.map(function(teacher) {
return {
name: teacher.title,
description: teacher.body_html,
image: urlToBase64(teacher.summary_html.match(/src="(.*?)"/)[1]),
city: metafieldTeacherData[teacher.id].city,
country: metafieldTeacherData[teacher.id].country,
state: metafieldTeacherData[teacher.id].state,
studioName: metafieldTeacherData[teacher.id].studioName,
studioURL: metafieldTeacherData[teacher.id].studioURL
}
});
该函数的实现看起来像
function urlToBase64(url) {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
return "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
}
});
}
我不清楚做到这一点的最佳方法是什么……承诺?嵌套回调?在ES6或ES7中使用一些东西然后用Babel进行转换?
目前实现这一目标的最佳方式是什么?
谢谢!
解决方法:
一种方法是Promise.all
(ES6).
这个答案适用于Node 4.0.旧版本需要Promise polyfill或库.我还使用了ES6箭头函数,你可以用Node<的常规函数替换它们. 4.
此技术使用Promise手动包装request.get.您也可以使用像request-promise这样的库.
function urlToBase64(url) {
return new Promise((resolve, reject) => {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve("data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64'));
} else {
reject(response);
}
});
})
}
// Map input data to an Array of Promises
let promises = input.map(element => {
return urlToBase64(element.image)
.then(base64 => {
element.base64Data = base64;
return element;
})
});
// Wait for all Promises to complete
Promise.all(promises)
.then(results => {
// Handle results
})
.catch(e => {
console.error(e);
})