Node.js:在调用resolve()之前解决了Promise?

时间:2016-07-09 00:54:55

标签: javascript node.js promise

我对Node.js及其异步行为的世界很新。

我正在尝试获取一个文件,保存它的副本,在复制的文件中添加一行并开始使用复制的文件 - 按顺序。

这大致是我现在所拥有的......

var first = new Promise(function(resolve, reject) {
    console.log("1");
    var readStream = fs.createReadStream("file.txt");
    var writeStream = fs.createWriteStream("file-copy.txt");
    readStream.on("end", function () {
        writeStream.end();
    });

    var pipeAction = readStream.pipe(writeStream);
    pipeAction.on("close", function() {
        console.log("2");
        resolve();
    });
});

var second = new Promise(function(resolve, reject) {
    console.log("3");
    fs.appendFile("file-copy.txt", "\nA NEW LINE TO INSERT",  function (err) {

    });
    console.log("4");
    resolve();
});

var third = new Promise(function(resolve, reject) {
    // do something with the modified, copied file
    console.log("5");
});

first.then(second).then(third);

输出显示1 3 4 5 2而不是1 2 3 4 5.任何人都可以分享为什么“第一”能够在打印“2”之前解决的问题?

谢谢!

1 个答案:

答案 0 :(得分:5)

您未正确使用promises。在您的示例中,您将立即调用您的承诺。由于它们的执行函数(带有resolve / reject params的回调)被称为实例化承诺的时刻,因此您立即记录1,3,4和5.自{{1包含在异步操作的回调中,它被推迟并最终被称为最后一次。

实施您尝试的方法的正确方法是将变量设置为函数本身,而console.log('2')代替您的承诺。这样,当您调用returnfirstsecond函数时,它们会立即调用其执行程序并启动控制流。你必须third承诺,否则你将打破承诺链。

return

收率:

function first() {
  return new Promise(function(resolve, reject) {
    console.log("1");
    var readStream = fs.createReadStream("file.txt");
    var writeStream = fs.createWriteStream("file-copy.txt");
    readStream.on("end", function() {
      writeStream.end();
    });

    var pipeAction = readStream.pipe(writeStream);
    pipeAction.on("close", function() {
      console.log("2");
      resolve();
    });
  });
}

function second() {
  return new Promise(function(resolve, reject) {
    console.log("3");
    fs.appendFile("file-copy.txt", "\nA NEW LINE TO INSERT", function(err) {

    });
    console.log("4");
    resolve();
  });
}

function third() {
  return new Promise(function(resolve, reject) {
    // do something with the modified, copied file
    console.log("5");
  });
}

first().then(second).then(third);

这是一个可以使用的工作版本:



1
2
3
4
5