【问题标题】:How to make use of async.applyEachSeries in node js?如何在节点 js 中使用 async.applyEachSeries?
【发布时间】:2016-10-26 01:57:10
【问题描述】:

如果有人能给出一个更具体的例子来说明如何使用 async.applyEachSeries 函数,我们将不胜感激。

async.applyEach([enableSearch, updateSchema], 'bucket', callback);

// partial application example:
async.each(
    buckets,
    async.applyEach([enableSearch, updateSchema]),
    callback
);

这是来自异步自述文件,但我不知道如何使用它。什么是'bucket',它只是一个被传递到某个地方的字符串吗?

【问题讨论】:

  • 所以你知道,你的代码示例使用applyEach,而你的问题标题提到applyEachSeries。我假设您想了解applyEachSeries,因为它们的用法相同。
  • 你的假设是正确的。
  • 我的回答对applyEachSeries() 有意义吗?代码 sn-ps 只使用了applyEach()each(),但如果在本例中使用applyEachSeries,它只会按顺序执行回调。
  • 是的,这是有道理的,但我仍然不能 100% 理解它,如果你能给出一个有竞争力的例子,那将会很有帮助。我从github.com/caolan/async#applyEachSeries复制并粘贴了这段代码sn-ps,
  • 我不太确定你想要什么例子。如果你在寻找applyEachSeries()而不是applyEach()的例子,它的用法基本上和applyEach()是一样的(虽然保证第一个参数传入的函数是按顺序执行的)。您是否在寻找更实用的 applyEachSeries() 示例?

标签: node.js asynchronous


【解决方案1】:
async.applyEach([enableSearch, updateSchema], 'bucket', callback);

这会通过回调异步调用enableSearch('bucket')updateSearch('bucket'),然后在它们都完成后调用callback()


// partial application example:
async.each(
    buckets,
    async.applyEach([enableSearch, updateSchema]),
    callback
);

async.applyEach() 调用返回一个函数,该函数在调用时使用其参数调用 enableSearch()updateSchema()。由于async.each() 的第一个参数应该是一个数组,我假设buckets 是一个字符串数组(因为第一个示例涉及将一个字符串传递给enableSearch()updateSearch())。因此,这可能会调用 enableSearch()updateSearch() 数组中的每个字符串 buckets(然后调用 callback())。

【讨论】:

  • 就我而言,回调不起作用。而async.applyEachSeries 只调用第一个函数enableSearch 并且没有回调。
【解决方案2】:

这是一个非常清晰的 async.applyEachSeries 示例:

applyEachSeries(tasks, args..., [callback])

示例:

function one(arg1, arg2, callback) {
    // Do something
    return callback();
}

function two(arg1, arg2, callback) {
    // Do something
    return callback();
}

async.applyEachSeries([one, two], 'argument 1', 'argument 2', function finalCallback(err) {
    // This will run after one and two
});

来源:https://stackoverflow.com/a/35309495

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多