【问题标题】:Node.js concat array after async.concat()async.concat() 之后的 Node.js 连接数组
【发布时间】:2013-07-16 03:22:04
【问题描述】:

我有一个数组,我需要使用一些编辑重新编译。我在async.concat() 的帮助下完成了这项工作,但有些东西不起作用。 告诉我,错在哪里?

async.concat(dialogs, function(dialog, callback) {
    if (dialog['viewer']['user_profile_image'] != null) {
        fs.exists(IM.pathToUserImage + dialog['viewer']['user_profile_image'].replace('%s', ''), function(exits) {
            if (exits) {
                dialog['viewer']['user_profile_image'] = dialog['viewer']['user_profile_image'].replace('%s', '');
            }
            callback(dialog);
        });
    }
}, function() {
    console.log(arguments);
});

在我看来,一切都是合乎逻辑的。在第一次迭代后立即调用回调。但是整个数组处理完成后如何发送数据呢?

谢谢!

【问题讨论】:

  • console.log 通话记录是什么?结果有什么意外?
  • @Bergi 在回调中只有一个数组元素。
  • 啊,那是因为你“抛出”了一个错误。请改用callback 的第二个参数。
  • @Bergi 寻找第一个答案。

标签: javascript node.js async.js


【解决方案1】:

你想要而不是callback(dialog);

callback(null,dialog);

因为回调函数的第一个参数是一个错误对象。在第一次迭代后调用console.log(arguments) 的原因是因为async 认为发生了错误。

【讨论】:

  • 我认为这并不重要。但即使这样也有问题,如果我在第一个参数null 中传递回调,callback 内部没有任何内容,即使console.log(arguments);
  • @RomanGorbatko:文档还说传递给callback 的第二个值应该是一个数组。看起来dialog 是一个对象?
  • 不,dialog 是一个对象。但是,如果做得好:callback (null, [dialog]),我们会得到同样的结果 - 什么都没有
  • 如果我作为第一个参数是空的,那么里面的callback,什么都不会发生,但是如果你传递类似123的东西 - 工作。
【解决方案2】:

我解决了这个问题,但不明白它的含义。问题是由于元素为 null 而不是处理后的值。程序此时中断,但不要丢弃任何错误/警告。

async.map(dialogs, function(dialog, callback) {
    if (dialog['viewer']['user_profile_image'] == null) {
        dialog['viewer']['user_profile_image'] = IM.pathToUserImage;
    }
    fs.exists(IM.pathToUserImage + dialog['viewer']['user_profile_image'].replace('%s', ''), function(exits) {
        if (exits) {
            dialog['viewer']['user_profile_image'] = dialog['viewer']['user_profile_image'].replace('%s', '');
        }
        callback(null, dialog);
    });
}, function(err, rows) {
    if (err) throw err;
    console.log(rows);
});

【讨论】:

  • 总是必须调用async传递给你的处理函数的回调函数。在您最初的示例中,如果 dialog['viewer']['user_profile_image'] 恰好是 null,您没有调用它。这可能会导致未定义的行为。
  • 你为什么在这里使用async.concat()而不是async.map()
  • @LeonidBeschastny 因为我需要将数组的所有元素收集为一个。但是,坦率地说,我不太明白.concat.map 之间的区别。
  • @robertklep 我很困惑node.js 没有抛出任何错误。
  • async.map 将数组的每个元素映射到一个新元素中,从而生成一个长度相同的新数组。 async.concat 将数组的每个元素映射到一个子元素数组中,然后将它们连接到一个数组中。因此,使用async.concat,您可以生成任意长度的数组,而async.map 将始终生成与原始数组长度相同的数组。
【解决方案3】:

虽然我发布这个答案有点晚了,但我发现我们都没有按照应有的方式使用 .concat 函数。

我已经创建了一个 sn-p 来说明这个函数的正确实现。

let async = require('async');
async.concat([1, 2, 3], hello, (err, result) => {
    if (err) throw err;
    console.log(result); // [1, 3]
});

function hello(time, callback) {
    setTimeout(function () {
        callback(time, null)
    }, time * 500);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-29
    • 2015-07-29
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多