使用承诺fullfilled,拒绝
问题描述:
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和正在研究有关承诺模块(?)。 这可能是一个非常基本的问题,但我无法找到全填充和拒绝方法获取参数值的位置。使用承诺fullfilled,拒绝
答
then()方法返回一个Promise。它最多需要两个参数:Promise的成功和失败情况的回调函数。
p.then(onFulfilled[, onRejected]);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
onFulfilled 如果承诺满足调用的函数。这个函数有一个参数,履行价值。 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为清楚起见
+0
哦!我明白谢谢 – dogyhbin2
答
要添加到@ marvel308的答案,无论你怎么称呼resolve()
用的是then
子句中可用,无论你怎么称呼的reject()
用的是catch
子句中使用。
考虑:
function makePromise(condition) {
return new Promise(function(resolve, reject) {
condition
? resolve('2 + 2 = 4')
: reject('No, wait. Maybe it is 5.')
})
}
现在,如果我们调用这个函数与resolve
情况:
并与reject
情况:
makePromise(false)
.then(x => console.log(x))
.catch(x => console.log(x)) // No, wait. Maybe it is 5.
*在fullfilled和拒绝方法获取参数的值* - 这是什么意思?你能否澄清你想知道的事情? – PeterMader
我的意思是fullfilled和被拒绝的方法获取参数结果和错误每个。 – dogyhbin2
你在这里通过拒绝('错误信息'); – marvel308