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

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

问题描述

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

I'm mapping over an array and for one of the return values of the new object, I need to make an async 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箭头函数,你可以用常规函数替换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.

此技术使用Promise手动包装 request.get 。您还可以使用请求承诺等库。

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天全站免登陆