Javascript 第二步,然后在promise中的第一步之前运行函数
这是我的代码:Javascript 第二步,然后在promise中的第一步之前运行函数,javascript,asynchronous,promise,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
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);
在本例中,我预计事情将按以下顺序发生:
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”函数之前,它将以异步顺序首先记录所有内容名称,这意味着所有承诺将一起执行。
有人能解释一下我做错了什么吗
谢谢你
。然后
接受函数作为参数,而不是调用函数的结果-即,在本例中,您将承诺传递给。然后
-承诺不是函数在中进行调用之前。然后
使用()=>
并退后观察Jaromanda X,非常感谢!)我真的不知道。。