让我们让代码来说话。假设我们有一个叫做promise1
. 根据规范:
从规格
然后必须返回一个承诺
自我解释:
promise2 = promise1.then(onFulfilled, onRejected);
从规格
如果 onFulfilled 或 onRejected 返回值 x,则运行 Promise Resolution Procedure [[Resolve]](promise2, x)。
如果我们有
promise2 = promise1.then(()=>123,()=>123);
然后你可以做
promise2.then((x)=> /* x should be 123 */, (x)=> /* will not be called */);
从规格
如果 onFulfilled 或 onRejected 抛出异常 e,则 promise2 必须以 e 为理由被拒绝。
如果我们有
promise2 = promise1.then(()=> { throw new Error('message'); }, ()=> { throw new Error('message'); });
然后你可以做
promise2.then((x)=> /* should not be called */, (x)=> /* x will be equal to "new Error('message')" */);
从规格
如果 onFulfilled 不是函数并且 promise1 已实现,则 promise2 必须以相同的值实现。
如果我们有
promise1 = new Promise(function(resolve,reject) { resolve(123) });
promise2 = promise1.then(null,null);
然后我们可以做
promise2.then((x)=> /* x should be 123 */, (x)=> /* should not be called */);
从规格
如果 onRejected 不是函数并且 promise1 被拒绝,则 promise2 必须以同样的理由被拒绝。
如果我们有
promise1 = new Promise(function(resolve,reject) { reject(123) });
promise2 = promise1.then(null,null);
然后我们可以做
promise2.then((x)=> /* should not be called */, (x)=> /* x should be 123 */);
要验证您是否实现编写测试,如图所示。我建议将 Mocha 与 Chai 一起使用。