[英]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.