【问题标题】:callback method while loop javascript循环javascript时的回调方法
【发布时间】:2018-05-11 01:16:59
【问题描述】:

我想在while 循环中使用回调函数,如下所示:

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

function() 不会被调用,但它可以在没有loop 的情况下工作。

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

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

【问题讨论】:

  • Methodwithcallback 是异步的吗?
  • 函数异步执行。
  • while循环的条件是什么?您能否确认该方法被忽略(例如在回调中记录)
  • 检查文件是否存在是一个无限循环。如果是,则应上传文件,并以计数器+1 重复循环。我可以确认该方法被忽略了。
  • 要么等待异步方法完成(这消除了异步的好处),要么让外部作用域也异步

标签: javascript node.js loops asynchronous callback


【解决方案1】:

您不能将循环与这样的异步函数一起使用 - 循环想要“现在”执行,而回调“稍后”执行..

试试这样的:

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

methodWithCallback(callback); // start the first one

【讨论】:

    【解决方案2】:

    您可以使用递归回调处理程序,该处理程序根据基本情况知道何时停止,在下面的代码中,它为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(),它将使用给定的异步函数串行迭代集合。

    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() 可以是promisified,那么我们可以稍微缩短这段代码。 Promisification 现在也通过 util.promisify() 内置到 Node 中

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

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多