I am learning about promises in JavaScript and encounter some weird thing
const successFunc = msg => {
console.log(`Success ${msg}`);
};
const failFunc = msg => {
console.log(`Fail ${msg}`);
};
// create a promise object
// inside the promise object, there is a logic gate inside.
const promise = new Promise((resolve, reject) => {
const a = 5;
const b = 1;
if (a > b) {
// it will call the resolve function
resolve();
} else {
// it will call the reject function
reject();
}
});
// // the promise object is activate and start when calling
// // this is actually an object chain promise.then(func).catch(func)
promise
.then(successFunc("calling successFun"))
.catch(failFunc("calling Fail Func"));
promise
.then(() => {
console.log("success");
})
.catch(() => {
console.log("fail");
});
In the first version, I expect this to return only the message from successFunc
but somehow, it will return both of them.
In the second version, the function is created inside instead globally, this somehow creates the behaviour I expect, which is calling success message only. Could someone provide more information about this behaviour?
This is the output:
>> node .\promise.js
Success calling successFun
Fail calling Fail Func
success