0

I have a code snippet like the following.

async.parallel({

    foo: function(call) {

      request.get('...?node=foo', function (error, response, body) {

        var last=JSON.parse(body);
        call(null,last.data.result);
      });

    },
    bar: function(call) {
      request.get('...node=bar', function (error, response, body) {

        var last=JSON.parse(body);
        call(null,last.data.result);
      });
    }
  }, function(err, results) {
    callback(results)
  });

but I want to that in loop...that is to say,like the following.

var node = ['foo', 'bar'];
async.parallel({

  for (var i = 0; i < node.length; i++) {
    node[i]: function(call) {

      request.get('...?node=' + node[i] + '', function(error, response, body) {

        var last = JSON.parse(body);
        call(null, last.data.result);
      });

    }
  }

}, function(err, results) {
  callback(results)
});

it does not work...how to make it? can you help me?

1

1 Answer 1

1

You have one of two options. One is to read the documentation for async.map(), which would be the more canonical approach using async.

That would look something like this:

async.map(['foo', 'bar'], function (node, callback) {
  request.get('...?node=' + encodeURIComponent(node), function (error, response, body) {
    if (error) return callback(error)
    var last = JSON.parse(body)
    callback(null, last.data.results)
  })
}, function (error, results) {
  // handle error
  callback(results)
})

Your second option would be to use Promise.all() with a synchronous Array#map(), removing the dependency for async entirely, though you'll probably want a polyfill like bluebird until Promises are used in more substantial percentage of browsers.

Here's how you'd implement the latter solution using native Promises:

Promise.all(['foo', 'bar'].map(function (node) {
  return new Promise(function (resolve, reject) {
    request.get('...?node=' + encodeURIComponent(node), function (error, response, body) {
      if (error) return reject(error)
      var last = JSON.parse(body)
      resolve(last.data.result)
    })
  })
})).then(function (results) {
  callback(results)
}).catch(function (error) {
  // handle error
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.