其次,函数在promise中的第一个函数之前运行

时间:2017-06-08 11:30:24

标签: javascript asynchronous promise

这是我的代码:

var fs = require('fs');

var printMsg = function (msg) {
    console.log("printMsg: " + msg)
};

var myWrite = function (filename, content) {
    return new Promise(function (resolve, reject) {
        fs.writeFile(filename, content, function (err) {
            console.log("content: " + content);
            if (err || content.includes('Fail')) {
               console.log("promise rejected for content: '" + content + "'");
               reject("error writing");
            }
            else {
               console.log("promise resolved for content: '" + content + "'");
               resolve("ok");
            }
        });
    });
};

myWrite("test.txt", "Hello world")
    .then(myWrite("test.txt", "Failed"))
    .then(myWrite("test.txt", "How are you?"))
    .catch(printMsg);

在这个例子中,我预计事情将按此顺序发生:

  1. 日志将打印内容" Hello world"
  2. 该功能用" ok"。
  3. 解决了它
  4. 日志将打印内容"失败"
  5. 该函数拒绝了它"错误写入"消息。
  6. 将跳过下一个承诺。
  7. catch将执行第二个promise,并显示消息"错误写入"
  8. 实际结果非常令人困惑,所有的promises都是异步的,所有的promises都没有catch函数。

    输出:

    content: Hello world
    promise resolved for content: 'Hello world'
    content: How are you?
    promise resolved for content: 'How are you?'
    content: Failed
    promise rejected for content: 'Failed'
    

    输出有时会发生变化,也可能是:

    content: How are you?
    promise resolved for content: 'How are you?'
    content: Hello world
    promise resolved for content: 'Hello world'
    content: Failed
    promise rejected for content: 'Failed'
    

    如果我在" writeFile"之前移动了内容的日志。函数,它将首先以异步顺序记录所有内容名称,这意味着所有承诺一起执行。 有人可以解释一下我做错了什么吗?

    感谢'!小号

0 个答案:

没有答案