2017-08-25 72 views
1

我需要在Dart中反覆調用異步函數,我們將其稱爲expensiveFunction,以獲取可變數目的參數。但是,由於每次調用都非常耗費內存,所以我不能並行運行它們。我如何強制他們順序運行?順序處理飛鏢中可變數量的異步函數

我已經試過這樣:

argList.forEach(await (int arg) async { 
    Completer c = new Completer(); 
    expensiveFunction(arg).then((result) { 
    // do something with the result 
    c.complete(); 
    }); 
    return c.future; 
}); 

,但一直沒有達到預期效果。對argList中的每個arg仍然並行調用expensiveFunction。我真正需要的是等待forEach循環,直到expensiveFunction完成,然後才能繼續執行argList中的下一個元素。我怎樣才能做到這一點?

回答

2

你要在這裏使用了經典for循環:

doThings() async { 
    for (var arg in argList) { 
    await expensiveFunction(arg).then((result) => ...); 
    } 
} 

有一些很好的例子on the language tour

+0

這麼簡單...我爲什麼沒有想到它?我設法通過遞歸來解決它,但是您的解決方案更加優雅。 –

+1

您也可以使用'Future.forEach(argList,expensiveFunction)'。 – lrn