【问题标题】:How to use async.eachSeries in nodeJS?如何在 nodeJS 中使用 async.eachSeries?
【发布时间】:2022-01-09 14:40:02
【问题描述】:

我想以同步方式遍历项目列表,并在下一步中使用每个步骤的结果。我可以有人更正/建议我正在使用的代码逻辑吗?

const async = require('async')

async.eachSeries([1, 2, 3, 4, 5],
  function downloadChunk (chunkID, asyncCallback) {
    console.log(chunkID)
    const result = `This is a result from ${chunkID} call and should be used somewhere in ${chunkID + 1}`
    // How should I pass this result to next step
    asyncCallback()
  },
  function complete (err) {
    if (err) console.log('Error: ' + err)
    console.log('this is the end. All the variables have been used')
  }
)

【问题讨论】:

  • async.eachSeries异步通过列表工作。也许是顺序的,但不是同步的。您的 downloadChunk 函数实际上是异步的吗?因为如果不是,只需使用普通循环即可。

标签: javascript node.js asynchronous each async.js


【解决方案1】:

您可以像这样在 async.eachSeries 之外简单地创建一个变量:

const async = require('async')
var result = null;

async.eachSeries([1, 2, 3, 4, 5],
    function downloadChunk (chunkID, asyncCallback) {
        console.log(chunkID)
        console.log('Result from previous call', result);

        // reassign new value to the result
        result = `This is a result from ${chunkID} call and should be used somewhere in ${chunkID + 1}`

        asyncCallback()
    },
    function complete (err) {
        if (err) console.log('Error: ' + err)
        console.log('this is the end. All the variables have been used')
    }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2018-02-09
    • 2016-06-22
    • 1970-01-01
    • 2019-02-14
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多