简体   繁体   English

兑现诺言,兑现诺言

[英]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);

I just started node.js and was studying about promise module(?). 我刚刚启动node.js,正在研究Promise模块(?)。 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. then()方法返回一个Promise。 It takes up to two arguments: callback functions for the success and failure cases of the Promise. 它最多包含两个参数:Promise成功和失败案例的回调函数。

p.then(onFulfilled[, onRejected]);

p.then(function(value) {
  // fulfillment
}, function(reason) {
  // rejection
});

onFulfilled A Function called if the Promise is fulfilled. onFulfilled一个函数,如果Promise被实现,则被调用。 This function has one argument, the fulfillment value. 此函数有一个参数,即实现值。 onRejected Optional A Function called if the Promise is rejected. onRejected可选如果Promise被拒绝,则调用一个函数。 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 为了清楚起见,请看p

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. 要添加到@ marvel308的答案中,那么在then子句中使用的是resolve()任何内容,在catch子句中可用的任何称为reject()的内容。

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: 现在,如果我们以resolve情况调用此函数:

makePromise(true)
.then(x => console.log(x)) // 2 + 2 = 4
.catch(x => console.log(x))

And with the reject case: 对于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM