我正在映射一个数组,对于新对象的返回值之一,我需要进行异步调用。
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');
}
});
}
我不清楚这样做的最佳方法是什么......Promise?嵌套回调?在 ES6 或 ES7 中使用某些东西,然后使用 Babel 进行编译?
目前实现这一目标的最佳方法是什么?