gpt4 book ai didi

javascript - Node.js Promises Q.all 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:55 24 4
gpt4 key购买 nike

我有这个 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 的工作原理吗?

最佳答案

这对你来说会更好。请阅读代码中的注释 - 实际上只是几行额外的代码,其中包括添加错误处理。

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

关于javascript - Node.js Promises Q.all 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com