简体   繁体   English

强制将javascript变量作为“值”传递

[英]Forcing javascript variable to be passed as “value”

I am having a problem with a classic javascript "issue"! 我在使用经典的javascript“问题”时遇到了问题!

I want to create an array of functions that will each be set to run after different lenghs of time (each one second apart). 我想创建一个函数数组,每个函数都将设置为在不同长的时间(相隔一秒)后运行。

However the following code is creating functions that all have the timeout set to the last value of timeout. 但是,以下代码创建的函数都将超时设置为超时的最后一个值。

Any help to solve this would be wonderful! 解决这个问题的任何帮助都会很棒! Thanks! 谢谢!

    var timeout = 0;
    var myfunctions = []

    urls.forEach(function(url){

      var newFunction = function(callback){
        (function (timeout){
          setTimeout(function(){
            getTransactions(url, function(err, data){
              callback(err, data)
            })
          },timeout)

        })(timeout)

      }
      timeout = timeout + 1000
      myfunctions.push(newFunction)
    })

The reason each function has a callback is that I that plan to run them all using: 每个函数都有一个回调的原因是我计划使用以下命令来运行它们:

    async.parallel(myfunctions,
      function(err, results) {
        if(err) {
          console.log(err.message)
        }
        else{
          console.log(results)
        }
      })

You've just misapplied the usual pattern; 您只是误用了通常的模式; you're doing it too far in, waiting to call the inner IIFE until your function is called, at which point timeout is already updated. 您将其做得太深了,等待调用内部IIFE,直到调用您的函数为止,此时已更新timeout

But there's no need for the IIFE at all, you can use the closure of the callback to forEach : 但是完全不需要IIFE,您可以使用对forEach的回调的关闭:

var timeout = 0;
var myfunctions = []

urls.forEach(function(url) {
    var thisTimeout = timeout;
    var newFunction = function(callback) {
        setTimeout(function() {
            getTransactions(url, function(err, data) {
                callback(err, data)
            })
        }, thisTimeout)
    };
    timeout = timeout + 1000
    myfunctions.push(newFunction)
});

Live Example: 现场示例:

 var timeout = 0; var myfunctions = []; var urls = ["first", "second", "third"]; urls.forEach(function(url) { var thisTimeout = timeout; var newFunction = function(callback) { console.log("url = " + url + ", thisTimeout = " + thisTimeout); /* setTimeout(function() { getTransactions(url, function(err, data) { callback(err, data) }) }, thisTimeout) */ }; timeout = timeout + 1000 myfunctions.push(newFunction) }); myfunctions.forEach(function(f) { f(); }); 

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

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