这是我的代码:
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);
在这个例子中,我预计事情将按此顺序发生:
实际结果非常令人困惑,所有的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"之前移动了内容的日志。函数,它将首先以异步顺序记录所有内容名称,这意味着所有承诺一起执行。 有人可以解释一下我做错了什么吗?
感谢'!小号