我在循环中调用了一个不“属于”我的异步函数。我需要在“then”函数中检索一个变量。这是我的做法:
for(var int = 0; int < attachments.length; int++) {
dp.getAttachment(attachments[int]).then(function (response) {
console.log(int);
});
}
如何发送 int 以便在函数中获取它?
最佳答案
问题是错误使用了closure variable in a loop .
这里因为你有一个数组,你可以使用 forEach() 创建一个本地闭包遍历它
attachments.forEach(function (item, it) {
dp.getAttachment(item).then(function (response) {
console.log(int);
});
})
关于javascript - 将变量传递给 promise 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690491/