【问题标题】:For loop in Async Programming [duplicate]异步编程中的 For 循环 [重复]
【发布时间】:2016-06-02 05:26:24
【问题描述】:
userId = ['123', '456'];
userName = ['aaa', 'bbb'];
for (var j = 0; j < userId.length; j++) {
            Instagram.otherUserMedia(userId[j], function (response) {
                $('#otherInfo').append('<h2>' + userName[j] + '</h2>');
                for(var i = 0; i < response.data.length; i++) {
                    $('#otherInfo').append('<img src="' + response.data[i].images.thumbnail.url + '" />');
                }
            });
        }

在这段代码 sn-p 中,我需要显示对应的 userName 和来自 response 的输出图像。但是当我执行这段代码时,j 的值会递增到userId.length,然后进入回调。 所以,当我想显示userName[j] 时,它说jundefined,因为它循环遍历userId 中的每个值。 我想为每个userIdresponse 获取对应的userName

【问题讨论】:

标签: javascript jquery node.js instagram-api asynccallback


【解决方案1】:

这是一个与 JavaScript Closure 相关的问题。

以下演示可能是解决方案之一;

userId = ['123', '456'];
userName = ['aaa', 'bbb'];
for (var j = 0; j < userId.length; j++) {
  Instagram.otherUserMedia(userId[j], (function(index) {
    return function(response) {
      $('#otherInfo').append('<h2>' + userName[index] + '</h2>');
      for (var i = 0; i < response.data.length; i++) {
        $('#otherInfo').append('<img src="' + response.data[i].images.thumbnail.url + '" />');
      };
    }
  }(j)));
}

您可能需要查看以下资源:
How do JavaScript closures work?
Closures
Immediately-Invoked Function Expression (IIFE)

【讨论】:

  • 成功了。谢谢!
猜你喜欢
  • 2017-02-25
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 2016-12-04
  • 2019-02-15
相关资源
最近更新 更多