JS Promise实例 then()方法

JS Promise实例 then()方法

内容已更新,可百度搜索: EC前端

描述:

then()方法用于指定当前实例状态发生改变时的回调函数。它返回一个新的Promise实例。

语法:

Promise.prototype.then(onFulfilled, onRejected);

参数:

参数描述
onFulfilled 当前实例变成fulfilled状态时,该参数作为回调函数被调用。
onRejected 当前实例变成reject状态时,该参数作为回调函数被调用。

返回值:

一个新的Promise实例。

注意:

onFulfilled将接收一个参数,参数值由当前Promise实例内部的resolve()方法传值决定;onRejected将接收一个参数,参数值由当前Promise实例内部的reject()方法传值决定。

例1:

const p = function(){
    let num = Math.random();
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            num > 0.5 ? resolve(num) : reject(num);
        }, 1000);
    })
};


p().then(val => {
    console.info(`Status switches to fulfilled, and the value is ${val}`);
}, val => {
    console.info(`Status switches to reject, and the value is ${val}`);
})

上面的例子中。若随机数大于0.5,Promise实例状态将转变成fulfilled,则then方法将调用第一个传入的回调函数;Promise实例状态将转变成reject,则then方法将调用第二个传入的回调函数;

例2:

const p = function(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('Refused the request!');
        },0);
    })
};

const p2 = function(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(p())
        },0);
    })
};

p2().then(val => {
    console.info('Status switches to fulfilled');
    console.info(val);
}, val => {
    console.info('Status switches to reject');
    console.info(val);
});

// 输出 "Status switches to reject"
// 输出 "Refused the request!"

上面的例子中:当Promise实例内部的fulfilled(或reject)传入的是Promise实例时,其状态以及then()方法的传值将由传入的Promise实例的状态决定。

转载至 Promise相关方法 - then()

原文地址:https://www.cnblogs.com/shaozhu520/p/10848474.html