编程go之Nodejs

Koa基础 Promise函数

2017-07-08  本文已影响14人  编程go
1. Promise 函数的特性

下面是一段Demo,

var checkUserName = function(name) {
    var promise = new Promise(function(resolve, reject) {
        if (name == 'Spursy')
            resolve('successed');
        else
            reject('failed');
    });

    return promise;
} 

checkUserName('Spursy').then(
    result => {
        console.log(`the result is ${result}.`);    // The result is successed.
}).catch(
    error => {
        console.log(`The error is ${error}.`);
    }
);
checkUserName('YY').then(
    result => {
        console.log(`the result is ${result}.`);
}).catch(
    error => {
        console.log(`The error is ${error}.`);     // The result is failed.
    }
);

从上面的Demo,可以看出生成的Promise 对象的实例并不会立即执行而是需要在实例对象调用then方法时才会执行Promise实例对象内部的方法体。

2. Promise.prototype.then()

then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。

checkUserName('YY').then(function(age) {
          return checkUserAge(age);
 }).then(
    result => {
        console.log(`the result is ${result}.`);
}).catch(
    error => {
        console.log(`The error is ${error}.`);     // The result is failed.
    }
);
3. Promise.prototype.all() 与 Promise.prototype.race()
var p = Promise.all([p1, p2, p3])
p.then(
    resolved => {}
).catch(
    error => {}
)
4. Promise.resolve() 与 Promise.reject()
Promise.resolve("Spursyy")
等价于
var p = new Promise(function(resolve, reject) {
    resolve("Spursyy");
})
Promise.reject("YY");
等价于
var p = new Promise(function(resolve, reject) {
    reject("YY");
})
上一篇下一篇

猜你喜欢

热点阅读