nodejs then()函数在promiseparsing之前执行
我有一个使Promise按预期工作的问题。 我需要做以下事情:
我从stdout中获取文件名,将它们分割成一行并复制它们。 当复制操作完成后,我想开始其他操作,这是我的问题。
我已经在Promise中创build了一个复制函数,万一出现错误,我立即拒绝它,如果没有错误,我在循环完成后解决它,但由于某种原因,在复制操作完成之前,
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(); }); }
请帮助,因为我明显失去了一些东西。
只要您打电话给resolve
,它就会得到resolve
,您在开始复制之后但在完成之前正在执行resolve
。 你必须等待最后的callback,然后再resolve
。 这意味着要logging下你看到的数量,看看***
评论:
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(); // *** } // *** } // *** }); } }); }
或者,有几个图书馆承诺 – 如果您使用Promise.all
风格的callback,那么您可以使用Promise.all
等标准承诺组合技术。 如果你正在使用其中的一种,你只需要做一些事情 :
function copyUpdatedFiles(lines) { return Promise.all( // CONCEPTUAL, semantics will depend on the promise wrapper lib lines.map(line => thePromiseWrapper(fs.copy, line, target)) ); }
注意:你的循环条件是指你的代码中没有定义的variableslinesLength
。 它应该是lines.length
。
在解决这个承诺之前,你不要等到复制成功,在for
,所有的fs.copy
都被放入调用堆栈,但是它们没有完成。
你可以在fs.copy
callback中使用一个计数器, fs.copy
调用一次callbackfs.copy
调用一次parsing,或者使用async 。
var async = require('async'); 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) { async.map(lines, (line, callback) => { fs.copy(line, target, (err) => { callback(err); }); }, (err) => { if(err) { reject(); } else { resolve(); } }); }); }