executing function on array using callbacks [close

2019-06-10 07:54发布

What is the correct way to call the same function on an array of objects using callbacks to advance?

Essentially processing asynchronous calls sequentially.

doAsynchFunction(data,callback){
 console.log(data);
 wait(1000,callback); // do something that takes some time and execute callback
}
var a=[1,2,3,4,5,6];

I'd like to see the numbers appear 1 second apart

2条回答
欢心
2楼-- · 2019-06-10 08:32

You could use Promise.all() to process asynchronous processes where the result could be returned in any order

var queue = [0, 1, 2, 3, 4, 5, 6, 7];

function asyncFn(n) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log("processing:", n)
      resolve(n)
    }, Math.random() * 3000)
  })
}

Promise.all(queue.map(function(value) {
    return asyncFn(value)
}))
.then(function(results) {
    console.log(results)
})
.catch(function(err) {
    console.log(err)
})

or use a queue to process asynchronous functions in sequential order

var queue = [0, 1, 2, 3, 4, 5, 6, 7]
, res = []
, queueCopy = queue.slice(0);

function asyncFn(n) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log("processing:", n)
      resolve(n)
    }, Math.random() * 3000)
  })
}

function processQueue(arr) {
  return asyncFn(arr.shift())
    .then(function(result) {
      res.push(result)
      if (arr.length) {
        return processQueue(arr)
      } else {
        return res
      }
    })
}

processQueue(queueCopy)
.then(function(results) {
    console.log(results)
})
.catch(function(err) {
    console.log(err)
})


Adjusting js at updated Question to utilizing setTimeout(), Function.prototype.bind() to pass function reference with parameters to setTimeout. Note, callback in this instance would be doAsynchFunction itself.

var a = [1, 2, 3, 4, 5, 6], aCopy = a.slice(0);

function wait(duration, callback) {
  setTimeout(function() {
    callback()
  }, duration)
}

function doAsynchFunction(arr, cb) {
  console.log(arr.shift());
  // pass `arr`, and `cb` : `doAsynchFunction` to `wait`
  if (arr.length) wait(1000, cb.bind(null, arr, cb)); 
}

doAsynchFunction(aCopy, doAsynchFunction);

查看更多
趁早两清
3楼-- · 2019-06-10 08:36

this is what I'm using right now

function run(onEnd){
    data=[1,2,3,4,5,6,7,8,9,10];
    var proc = function(){
        if(i<data.length){
            dosomething(data[i],proc);
        }else{
            onEnd()
        }
        i++;
    }
    proc();
}
查看更多
登录 后发表回答