简体   繁体   English

在Node Js中依次使用不同的参数多次运行一个函数

[英]Run a function multiple times with different arguments sequentially in Node Js

I have an array with values and I want to run a single function with a callback with each of the array's values as an argument sequentially. 我有一个带有值的数组,我想运行一个带有回调的函数,该数组的每个值都按顺序作为参数进行回调。 Meaning, run the function with the first cell's value, when it finishes run the function with the second's cell value etc. I tried with Q and I can't seem to find a way to do it with arguments, it keeps calling the function. 意思是,使用第一个单元格的值运行该函数,完成后使用第二个单元格的值运行该函数,以此类推。我尝试使用Q,但似乎找不到用参数执行此操作的方法,它一直在调用该函数。

Example: 例:

var array = [1,2,3,4,5]

var func1 = function(num){
  setTimeout(function(){
    console.log(num+num);
  }, 3000);
}

I want to run the function with 1 as argument, when it finishes run with 2 as argument etc 我想以1作为参数运行该函数,完成后以2作为参数运行等

Please notice that I want to run it sequentially. 请注意,我要按顺序运行它。

Thanks! 谢谢!

Use array.map 使用array.map

var array = [1,2,3,4,5]

var func1 = function(num){
  console.log(num+num);
}
array.map(func1)

Simply use a forEach 只需使用forEach

var array = [1,2,3,4,5]
var func1 = function(num){
  console.log(num+num);
}
array.forEach(func1);

And with Promise somethig like (not working code, just giving ideas) : 并且使用Promise之类的东西(不是有效的代码,只是给出想法):

var array = [1,2,3,4,5]
var func1 = function(num){
     var p = new Deferred();
     setTimeout(function(){
         console.log(num+num);
         p.resolve(num+num)
     }, 3000);
     return p;
}
var count = 0;
function next() {
    func1(array[count++]).then(next);
}

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

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