promise(5)promise.then()返回的新promise的结果状态由什么来决定

简单表达

.由then()指定的回调函数执行的结果决定

详细表达

2、详细表达:
* 2.1、如果抛出异常:新的promise变为rejected,reason为抛出的异常
* 2.2、如果返回的是非promise的任意值,新的promise变为resolved,value为返回的值
* 2.3、如果返回的是另一个新的promise,此promise的结果就成为新promise的结果

例一:抛出异常

 const p1 = new Promise((resolve,reject) => {   
        //假设异步任务执行失败
        reject('异步任务与执行失败的数据');
    })
    .then(
        value1 => {console.log('value1:' + value1);},
        reason1 => {
            console.log('reason1: ' + reason1);
            throw '抛出异常';
        }
    )
    .then(
        value2 => {console.log('value2:' + value2);},
        reason2 => {console.log('reason2' + reason2);}
    )

运行结果:

reason1: 异步任务与执行失败的数据
reason2抛出异常

例二:如果返回的是非promise的任意值

  const p1 = new Promise((resolve,reject) => {
        //假设异步任务执行失败
        reject('异步任务与执行失败的数据');
    })
    .then(
        value1 => {console.log('value1:' + value1);},
        reason1 => {console.log('reason1: ' + reason1);}//默认返回undefined
    )
    .then(
        value2 => {console.log('value2:' + value2);},
        reason2 => {console.log('reason2' + reason2);}
    )

运行结果:

reason1: 异步任务与执行失败的数据
value2:undefined

 const p1 = new Promise((resolve,reject) => {   
        //假设异步任务执行失败
        reject('异步任务与执行失败的数据');
    })
    .then(
        value1 => {console.log('value1:' + value1);},
        reason1 => {
            console.log('reason1: ' + reason1);
            return 2;
        }
    )
    .then(
        value2 => {console.log('value2:' + value2);},
        reason2 => {console.log('reason2' + reason2);}
    )

运行结果:

reason1: 异步任务与执行失败的数据
value2:2

例三:返回的是另一个新的promise

 const p1 = new Promise((resolve,reject) => {   
        //假设异步任务执行失败
        reject('异步任务与执行失败的数据');
    })
    .then(
        value1 => {console.log('value1:' + value1);},
        reason1 => {
            console.log('reason1: ' + reason1);
           return Promise.resolve('2'); // 返回一个成功值为2的promise对象
        }
    )
    .then(
        value2 => {console.log('value2:' + value2);},
        reason2 => {console.log('reason2' + reason2);}
    )

运行结果:

reason1: 异步任务与执行失败的数据
value2:2

 const p1 = new Promise((resolve,reject) => {   
        //假设异步任务执行失败
        reject('异步任务与执行失败的数据');
    })
    .then(
        value1 => {console.log('value1:' + value1);},
        reason1 => {
            console.log('reason1: ' + reason1);
           return Promise.reject('2'); // 返回一个失败值为2的promise对象
        }
    )
    .then(
        value2 => {console.log('value2:' + value2);},
        reason2 => {console.log('reason2' + reason2);}
    )

运行结果:

reason1: 异步任务与执行失败的数据
reason2:2

你可能感兴趣的:(promise)