2016-03-03 74 views
0

使用回調函數在對象數組上調用相同函數的正確方法是什麼?使用回調函數在數組上執行函數

基本上是按順序處理異步調用。

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]; 

我想看到的數字顯示除了

+0

你看着myArray.map(myFunction的) ? –

+0

你能更詳細地解釋你的問題陳述嗎? – Rajesh

+0

map()在繼續下一個函數之前是否等待第一個函數完成? – Daniel

回答

1

你可以使用Promise.all()處理在其結果可能以任何順序

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) 
 
})

返回異步進程1秒

或使用隊列按順序處理異步函數

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) 
 
})


在更新的問題調整js到利用setTimeout()Function.prototype.bind()傳遞與參數setTimeout函數參照。請注意,在這種情況下callback本身就是doAsynchFunction

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);

+0

@Daniel查看更新後的文章 – guest271314

+0

我認爲等待可能會令人困惑,關鍵是該函數是異步和順序的,所以需要處理第一個函數,這可能需要一秒鐘。有一段時間,我認爲這是更復雜的,然後我去了,但我認爲這只是因爲你包含等待函數有工作代碼。 – Daniel

0

這是我使用的是什麼,現在

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(); 
}