1

有没有办法将信息传递给 async.js 并行调用,所以我不必使用全局变量?

async.parallel([
  function(callback){
      setTimeout(function(){
          callback(null, 'one');
      }, 200);
  },
    function(callback){
      setTimeout(function(){
          callback(null, 'two');
      }, 100);
  },
],
// optional callback
function(err, results){
  console.log(info)
    // the results array will equal ['one','two'] even though
  // the second function had a shorter timeout.
});

我希望最终回调知道“信息”的值。谢谢你的帮助!

4

2 回答 2

1

To avoid introducing a global variable you could place it within an enclosure:-

(function() {
    var info = "Some info";

    async.parallel([
        function(callback) {
            setTimeout(function() {
                callback(null, "one");
            }, 200);
        }, 
        function(callback) {
            setTimeout(function() {
                callback(null, "two");
            }, 100);
        }
    ], 
    function(error, result) {
        console.log(info);
    });

}) ();

That way the final callback has access to it but it won't be visible outside of the scope of the anonymous self-executing function that encloses that code.

EDIT To do an enclosure in coffeescript:-

(() ->
  # my code
)()
于 2012-12-03T23:35:56.363 回答
0

另一种方法是:

(function(protectedVariable1,protectedVariable2) {
    //do something with protected variables
})(variable1,variable2);
于 2013-12-30T04:47:48.753 回答