【问题标题】:Node.js Promises Q.all is not workingNode.js 承诺 Q.all 不起作用
【发布时间】:2014-03-04 23:05:03
【问题描述】:

我有这个 readLines 函数来逐行解析调用自:

var fs = require('fs');
var Q = require('q');

Q.all(readLines(fs.createReadStream("/tmp/test.txt"), console.log)).then(function () {
    console.log('Done');
};

function readLines(input, func) {
    var remaining = '';

    input.on('data', function (data) {
        remaining += data;
        var index = remaining.indexOf('\n');
        while (index > -1) {
            var line = remaining.substring(0, index);
            remaining = remaining.substring(index + 1);
            func(line);
            index = remaining.indexOf('\n');
        }
    });

    input.on('end', function () {
        if (remaining.length > 0) {
            func(remaining);
        }
    });
};

谁能帮助我为什么从来没有“完成”?有什么教程可以了解 Promise 的工作原理吗?

【问题讨论】:

标签: javascript node.js promise q


【解决方案1】:

这将更适合您。请阅读代码中的 cmets - 实际上只有几行额外的内容,其中包括添加错误处理。

var fs = require('fs');
var Q = require('q');

// you don't need Q.all unless you are looking for it to resolve multiple promises.
// Since readlines returns a promise (a thenable), you can just then() it.
readLines(fs.createReadStream("./vow.js"), console.log).then(function (x) {
    console.log('Done',  x);
});

function readLines(input, func) {
    // you need to create your own deferred in this case - use Q.defer()
    var deferred = Q.defer();
    var remaining = '';

    input.on('data', function(data) {
        remaining += data;
        var index = remaining.indexOf('\n');
        while (index > -1) {
            var line = remaining.substring(0, index);
            remaining = remaining.substring(index + 1);
            func(line); 
            index = remaining.indexOf('\n');
        }
    });

    input.on('end', function() {
        if (remaining.length > 0) {
            func(remaining);
            console.log('done');
        }
        // since you're done, you would resolve the promise, passing back the 
        // thing that would be passed to the next part of the chain, e.g. .then()
        deferred.resolve("Wouldn't you want to return something to 'then' with?");
    });

    input.on('error', function() {
        console.log('bother');
        // if you have an error, you reject - passing an error that could be
        // be caught by .catch() or .fail()
        deferred.reject(new Error('Regrettable news - an error occured.'));
    });
    // you return the promise from the deferred - not the deferred itself
    return deferred.promise;
};

【讨论】:

  • Q.all 在那里做什么?
  • 实际上,除了浪费执行时间之外没有太多。好点 - 在这种情况下是多余的,因为只有一个承诺可以解决。现在编辑。具有讽刺意味的是,正是您对 OP 的评论“重新阅读 Q,all() 期望作为参数的内容”促使我只看它被调用的内容,而不是它在这里的实际用处。
  • 不客气。很高兴有帮助。关于上面 Bergi 和我自己之间的交流——Q.all() 通常是为了接受一个数组(承诺)。 Q.all() 否则将失败 - 一旦其成员承诺之一被拒绝。你可以使用Q.allSettled(),如果你想让它尝试解决所有的承诺,即使一个失败了。
猜你喜欢
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 2016-03-04
  • 2015-07-26
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 2014-02-02
相关资源
最近更新 更多