将variables传递给promise函数

我在一个循环内调用一个不属于我的asynchronous函数。 我需要在'then'函数中获取一个variables。 下面是我如何做到这一点:

for(var int = 0; int < attachments.length; int++) { dp.getAttachment(attachments[int]).then(function (response) { console.log(int); }); } 

我怎样才能发送的int,所以我可以得到它的function?

问题是在循环中错误地使用了一个闭包variables 。

这里既然你有一个数组,你可以使用forEach()来遍历它来创build一个本地的闭包

 attachments.forEach(function (item, it) { dp.getAttachment(item).then(function (response) { console.log(int); }); }) 
  • 循环中的JavaScript闭包 – 一个简单实用的例子

使用闭包的强大function,可以确保在调用callback函数时, intvariables的每个值的副本都可用。

 for(var int = 0; int < attachments.length; int++) { (function(int) { dp.getAttachment(attachments[int]).then(function (response) { console.log(int); }); })(int); }