简体   繁体   English

JSHint:循环中的异步功能

[英]JSHint: Asynchronous function in loop

I placed an asynchronous callback function (something like $.ajax ) inside a for loop. 我在for循环中放置了一个异步回调函数(类似$.ajax )。 It looked more or less like (edit: updated code, see comments): 它看起来或多或少像(编辑:更新的代码,请参阅注释):

var i = 0;

for ( ; i < 5; i++ ) {
  (function( index ) {
    $.ajax({
      url: "",
      success: function() {
        console.log( index );
      }
    });
  })( i );
}

It worked, but JSHint gave me a warning saying something like: 它起作用了,但是JSHint给我一个警告,说:

"Don't place functions inside loops" “不要将函数放在循环内”

Normally I could just place my callback function outside my loop and call that function for every iteration. 通常,我可以将callback函数放在循环之外,并在每次迭代时都调用该函数。 Unfortunately I need access to variables, which are assigned inside the loop (eg i ). 不幸的是,我需要访问在循环内分配的变量(例如i )。 So I'm looking for a solution to do something like below: 因此,我正在寻找一种解决方案,例如:

var i = 0;

function callback( data ) {
  // I want to have access to "i" (0, 1, 2, 3, 4) and the AJAX "data"
  // in this function. But I only have access to "data", because "i"
  // will always be 5
}

for ( ; i < 5; i++ ) {
  $.ajax({
    url: "",
    success: callback
  });
}

In this case you can use a function that returns a function that has access to the data you need. 在这种情况下,您可以使用一个函数,该函数返回可以访问所需数据的函数。

var i = 0;
function callback( i ) {
  return function (data) {
    // I want to have access to "i" (0, 1, 2, 3, 4) and the AJAX "data"
    // in this function.
    console.log(i)
  }
}

for ( ; i < 5; i++ ) {
  $.ajax({
    url: "",
    success: callback(i)
  });
}

however, it would of course be better to submit this data with a single request rather than looping. 但是,当然最好只发送一个请求而不是循环提交此数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM