nodejs then()函数在promise解析之前执行 [英] nodejs then() function executed before promise resolve
问题描述
我有一个让Promise按预期工作的问题。我需要做以下事情:
I have a problem with making Promise working as expected. I need to do following thing:
我从stdout获取文件名,将它们分成行并复制它们。复制操作完成后,我想开始其他操作,这是我的问题。
I get file names from stdout, split them into line and copy them. When copy operation is finished i want to start other operations and here is my problem.
我在Promise中创建了一个复制函数,如果出现错误我会立即拒绝它,如果没有错误我会在复制循环完成后解决它但对于某些在复制操作完成之前执行then()内部函数的原因
I've created a copy function inside Promise, in case of error i reject it immediately, if thereare no errors i resolve it after copy in loop is finished but for some reason the function inside then() gets executed before copy operation is done
var lines = stdout.split(/\r?\n/);
copyUpdatedFiles(lines).then(
function() {
console.log('this one should be executed after copy operation');
}
);
function copyUpdatedFiles(lines) {
return new Promise(function(resolve, reject) {
for (var i = 0; i < linesLength; i++) {
fs.copy(lines[i], target, function(err) {
if (err) {
reject();
}
});
}
resolve();
});
}
请帮助我明显遗漏一些东西。
Please help cause i'm clearly missing something.
推荐答案
一旦你打电话给解决
,你就会解决这个问题。 >开始副本,但在完成之前。在 resolve
之前,您必须等待最后一次回调。这意味着要跟踪您看到的数量,请参阅 ***
评论:
It gets resolved as soon as you call resolve
, which you're doing after starting the copies but before they finish. You have to wait for the last callback before you resolve
. That means keeping track of how many you've see, see the ***
comments:
function copyUpdatedFiles(lines) {
return new Promise(function(resolve, reject) {
var callbacks = 0; // ***
for (var i = 0; i < linesLength; i++) {
fs.copy(lines[i], target, function(err) {
if (err) {
reject();
} else { // ***
if (++callbacks == lines.length) { // ***
resolve(); // ***
} // ***
} // ***
});
}
});
}
或者,有一个那些承诺 - 如果是NodeJS风格的回调的库,所以你可以使用标准的承诺组合技术,如 Promise.all
。如果您使用其中一个,那么您只需 这个:
Alternately, there are a couple of libraries out there that promise-ify NodeJS-style callbacks so you can use standard promise composition techniques like Promise.all
. If you were using one of those, you'd just do something this:
function copyUpdatedFiles(lines) {
return Promise.all(
// CONCEPTUAL, semantics will depend on the promise wrapper lib
lines.map(line => thePromiseWrapper(fs.copy, line, target))
);
}
旁注:你的循环condition是指在代码中未定义的变量 linesLength
。它应该是 lines.length
。
这篇关于nodejs then()函数在promise解析之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!