让我们让代码进行谈话。可以说我们有一个叫做promise1
的承诺。根据规范:
从规格
则必须返回一个承诺
自我explainatory:
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 */);
要验证是否执行写入测试,如图所示。我建议与Chai一起使用Mocha。
为什么不运行测试套件? –
快速浏览代码至少有2个错误:你的'.then()'返回'this'(这实际上不仅是一个错误,而且错过了promise的全部点),并且你没有try catch围绕'x.then'。从https://github.com/promises-aplus/promises-tests运行测试套件。 – Esailija
我试了好几个小时来使用测试套件来测试我的实现,我重写了它,但没办法,仍然失败了很多有关then方法与对象的测试。这是新的代码:https://gist.github.com/ilmattodel93/dbefa9eb86715f76e10e/082cd93623e061727df728a9993e4f24caf24597仍然失败了很多测试:/为什么?我已经实现了代码,因为规范说...我想。 :/ –