callback方法while循环javascript

我想在这样的while循环中使用callback函数:

 do { Methodwithcallback(..function () { //do something }); } while (); 

function()不会被调用,但它没有loop工作。

该方法需要一些时间来执行,我想在方法完成后重复loop

为什么方法在loop被忽略? 我正在使用Node.js

你不能像这样使用asynchronous函数循环 – 循环想要执行“now”,callback执行“later”。

试试这样的事情:

 function callback() { // do whatever else is needed methodWithCallback(callback); // start the next one } methodWithCallback(callback); // start the first one 

您可以使用recursioncallback处理程序知道何时基于基本情况停止,在下面的代码中它为arr每个项目执行一次。 你也可以使用async.series()这是一个预制库来处理这个问题。

 const arr = [...items] let count = 0 const blockingHandler = () => { // Keep track of times invoked count++ // Do something // If there is another item to execute, then do it if (count < arr.length) { MethodwithCallback(blockingHandler)) } } MethodwithCallback(blockingHandler) 

如果你想使用Promises, bluebirdmapSeries() ,它将连续地迭代具有给定asynchronous函数的集合。

 const Promise = require('bluebird') const arr = [...items] Promise.mapSeries(arr, i => { MethodwithCallback(() => { /* * If there was some error handling you could check for an error * if there is one, then return a rejected Promise * if (err) { * return Promise.reject(err) * } */ // do something return Promise.resolve() }) }) .then(() => console.log('All Promises Complete')) .catch(err => console.log('An error occurred', err)) 

如果MethodwithCallback()可以被赋值 ,那么我们可以缩短这个代码。 Promisification现在也被构build到Node中,通过util.promisify()

 const Promise = require('bluebird') const asyncMethod = Promise.promisify(MethodwithCallback) const arr = [...items] Promise.mapSeries(arr, i => { return asyncMethod() .then(() => { // do something specific for this item }) }) .then(() => { // do something when all items done }) .catch(err => { // An error occurred during mapSeries console.log('An error occurred', err) })