在地图中调用异步函数的最佳方法? [英] Best way to call an asynchronous function within map?

查看:58
本文介绍了在地图中调用异步函数的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在映射一个数组,对于新对象的返回值之一,我需要进行异步调用.

I'm mapping over an array and for one of the return values of the new object, I need to make an asynchronous call.

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 进行编译?

I'm not clear what's the best approach to do this... promises? Nested callbacks? Use something in ES6 or ES7 and then transpile with Babel?

目前实现这一目标的最佳方法是什么?

What's the current best way to implement this?

推荐答案

一种方法是 Promise.all (ES6).

One approach is Promise.all (ES6).

此答案适用于 Node 4.0+.旧版本需要 Promise polyfill 或库.我还使用了 ES6 箭头函数,你可以用常规的 function 替换 Node <4.

This answer will work in Node 4.0+. Older versions will need a Promise polyfill or library. I have also used ES6 arrow functions, which you could replace with regular functions for Node < 4.

此技术手动将 request.get 与 Promise 包装在一起.您还可以使用像 request-promise 之类的库.

This technique manually wraps request.get with a Promise. You could also use a library like 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);
  })

这篇关于在地图中调用异步函数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆