将一组函数异步到一个数组

时间:2017-10-11 11:24:56

标签: javascript node.js asynchronous

所以我有一个包含四个JSON对象的数组,我想为每个对象添加三个新字段。为此,我为每个要添加的新字段设置了一个异步函数。理想情况下,我想要做的是将异步功能限制为每个只有2个更新。然后在最后,回调原始函数并打印出新形成的数组。但我不能让这个工作,虽然我觉得我很接近......

var async = require('async');

// My Array of JSON objects
var allIssues = [
    { id: '1', color: 'blue' },
    { id: '2', color: 'red' },
    { id: '3', color: 'gold' }
];

addExtraFeaturesToEachissue(allIssues, function(data) { console.log(data); });

function addExtraFeaturesToEachissue(allIssues, callback) {
    async.each(
        allIssues,
        async.applyEach([addheight, addWidth, addWeight]),
        callback(data)
    );
}

function addHeight(issue, callback) {
    setTimeout(function() {
        issue.fields['height'] = "1000";
        callback(issue);
    }, 100);
} 
function addWidth(issue, callback) {
    setTimeout(function() {
        issue['width'] = "100";
        callback(issue);
    }, 300);    
}
function addWeight(issue, callback) {
    setTimeout(function() {
        issue.['weight'] = "500";
        callback(issue);
    }, 200);
}

1 个答案:

答案 0 :(得分:2)

假设被调用的函数将执行一些长任务,老实说我没有看到使用异步的需要,为什么不只使用Promise?

// My Array of JSON objects
var allIssues = [
    { id: '1', color: 'blue' },
    { id: '2', color: 'red' },
    { id: '3', color: 'gold' }
];

addExtraFeaturesToEachissue(allIssues, function(data) { console.log(data); });

function addExtraFeaturesToEachissue(allIssues, callback) {
  var requests = allIssues.map((issue) => {
    return addHeight(issue).then(addWidth).then(addWeight);
  });
  Promise.all(requests).then((data) => console.log('done', data));
}

function addHeight(issue) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      issue.height = "1000";
      resolve(issue);
    }, 100);
});
}
function addWidth(issue) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
        issue.width = "100";
        resolve(issue);
    }, 300);
  });
}
function addWeight(issue) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
        issue.weight = "500";
        resolve(issue);
    }, 200);
  });
}

编辑我刚刚看到你最后完成了整个阵列。正如Jared Smith所建议的那样,你可以使用Promise.all;)