[英]using promise fulfilled, rejected
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);
我刚刚启动node.js,正在研究Promise模块(?)。 这可能是一个非常基本的问题,但是我找不到在哪里实现和拒绝的方法可以获取参数的值。
then()方法返回一个Promise。 它最多包含两个参数:Promise成功和失败案例的回调函数。
p.then(onFulfilled[, onRejected]);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
onFulfilled一个函数,如果Promise被实现,则被调用。 此函数有一个参数,即实现值。 onRejected可选如果Promise被拒绝,则调用一个函数。 此函数有一个参数,即拒绝原因。
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);
}
})
}
为了清楚起见,请看p
要添加到@ marvel308的答案中,那么在then
子句中使用的是resolve()
任何内容,在catch
子句中可用的任何称为reject()
的内容。
考虑:
function makePromise(condition) {
return new Promise(function(resolve, reject) {
condition
? resolve('2 + 2 = 4')
: reject('No, wait. Maybe it is 5.')
})
}
现在,如果我们以resolve
情况调用此函数:
makePromise(true)
.then(x => console.log(x)) // 2 + 2 = 4
.catch(x => console.log(x))
对于reject
情况:
makePromise(false)
.then(x => console.log(x))
.catch(x => console.log(x)) // No, wait. Maybe it is 5.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.