function task1(fullfill, reject) {
console.log('Task1 start');
setTimeout(function() {
console.log('Task1 end');
//fullfill('Task1 result');
reject('Error msg');
}, 300);
}
function fullfilled(result) {
console.log('fullfilled : ', result);
}
function rejected(err) {
console.log('rejected : ', err);
}
new Promise(task1).then(fullfilled, rejected);
I just started node.js and was studying about promise module(?). It could be a very basic question but I couldn't found out where the fulfilled and rejected method gets the parameter's value.
The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
p.then(onFulfilled[, onRejected]);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
onFulfilled A Function called if the Promise is fulfilled. This function has one argument, the fulfillment value. onRejected Optional A Function called if the Promise is rejected. This function has one argument, the rejection reason.
let p = function(){
return new Promise(function(resolve, reject) {
if(condition){
// this arg would be caught in onFulfilled
resolve(arg);
}
else{
// this arg would be caught in onRejected
reject(arg2);
}
})
}
take a look at p for clarity
To add to @marvel308's answer, whatever you call resolve()
with is available in the then
clause and whatever you call the reject()
with is available in the catch
clause.
Consider:
function makePromise(condition) {
return new Promise(function(resolve, reject) {
condition
? resolve('2 + 2 = 4')
: reject('No, wait. Maybe it is 5.')
})
}
Now, if we call this function with the resolve
case:
makePromise(true)
.then(x => console.log(x)) // 2 + 2 = 4
.catch(x => console.log(x))
And with the reject
case:
makePromise(false)
.then(x => console.log(x))
.catch(x => console.log(x)) // No, wait. Maybe it is 5.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.