Passing changing value to asynchronous function

2019-06-11 17:00发布

In the code below, I am adding a value to comb, trying to use that value in an asynchronous function, and then changing the value of comb. The value of comb within request is not as desired since comb.pop() occurs multiple times before request's callback fires. After searching many questions on stack overflow, I have tried putting a closure around request that took comb as input, but that did not work. How should I go about this?

comb = [1,2,3];
arr = [10,20,30];
promises = [];
for (var i = 0; i < arr.length; i++) {
    comb.push(arr[i]);

    var promise = new Promise(function(resolve, reject) {
        request(url, function(err, res, body) {
            // use comb
            if (/* comb meets certain condition */)
                resolve(body);
        });
    });
    promises.push(promise);

    comb.pop();
}

Here is my attempt at using a closure, which did not work:

var promise = new Promise(function(resolve, reject) {
    (function(comb) {
        request(url, function(err, res, body) {
            // use comb
            if (/* comb meets certain condition */)
                resolve(body);
        });
    })(comb);
});

1条回答
贼婆χ
2楼-- · 2019-06-11 17:47

This will work for simple types:

  var promise = (function(combCopy){
     var ret = new Promise(function(resolve, reject) {
          request(url, function(err, res, body) {
              //comb refers to the outside comb
              //combCopy refers to the copy
          });
      });
     return ret;
   })(comb);

Objects are always passed by references so passing an object as a parameter won't copy the object. You'll need to do that manually.

   var promise = (function(){ 
     //this creates a new scope -- something that might not be necessary
     var combCopy = Array.prototype.slice.call(comb); //shallow-only
     var ret = new Promise(function(resolve, reject) {
          request(url, function(err, res, body) {
              //comb refers to the outside comb
              //combCopy refers to the copy
          });
      });
      return ret;
   })();
查看更多
登录 后发表回答