在下面的代码中,我向comb添加一个值,尝试在异步函数中使用该值,然后更改comb的值。请求中的comb值不是所希望的,因为在请求的回调触发之前,comb.pop()会多次出现。在搜索了关于堆栈溢出的许多问题之后,我已经尝试在将请求作为输入的请求中放置一个闭包,但是这不起作用。我应该怎么做呢?
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();
}
这是我尝试使用一个无效的闭包:
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);
});
答案 0 :(得分:0)
这适用于简单类型:
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);
对象始终通过引用传递,因此将对象作为参数传递将不会复制对象。您需要手动执行此操作。
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;
})();