[英]javascript promise for calculator function
一直在试图解决这个编码挑战,我碰壁了。 要么让我头疼,要么我只是想念一些明显的东西。 下面是到目前为止我要尝试创建的函数所需要的代码以及mocha测试。
//设置摩卡和柴
mocha.setup( "bdd" );
var expect = chai.expect;
class Calculator {
add(x, y) {
return x + y;
}
subtract(x, y) {
return x - y;
}
multiply(x, y) {
return x * y;
}
divide(x, y) {
if(y === 0) {
return NaN;
} else {
return x / y
}
}
calculate(...args) {
var result = 0;
return new Promise(function(resolve, reject){
setTimeout(function() {
if(result === NaN) {
reject();
} else {
resolve();
}
}, 1000);
});
}
}
/ ** * 4.向符合此规范的计算器添加一个计算功能* /
describe( "Calculator.calculate", function(){
var calculator;
beforeEach( function(){
calculator = new Calculator();
} );
it( "returns a promise", function(){
var calculating = calculator.calculate( function(){} );
expect( calculating ).to.be.instanceOf( Promise );
} );
it( "resolves when the calculation succeeds", function( done ){
var calculating = calculator.calculate( function(){
expect( this ).to.equal( calculator );
var result = 0;
result += this.add( 1, 2 );
result += this.add( 3, 4 );
return result;
} );
calculating.then( function( result ){
expect( result ).to.equal( 10 );
done();
} );
} );
it( "rejects when the calculation fails", function( done ){
var calculating = calculator.calculate();
calculating.catch( function( result ){
expect( result ).to.be.NaN;
done();
} );
} );
} );
//运行测试
mocha.run();
计算器类用于其他测试。 我在计算功能上遇到麻烦,无法通过底部的测试。 有什么想法或见解吗?
**这是我得到的错误-错误:超时超过2000毫秒。 对于异步测试和挂钩,请确保调用了“ done()”; 如果返回承诺,请确保其解决。 https://cdnjs.cloudflare.com/ajax/libs/mocha/4.0.1/mocha.min.js:1:38622
谢谢!
您的代码有点混乱,但是我使用您的代码为您提供了一个示例,说明如何对计算器功能作出承诺。
promise函数必须始终包装异步函数。 然后,无论是否有错误,您都调用相应的resolve
或reject
。
/* First define the calculator with the promise*/ function calculateDivision(x,y, time) { var result = 0; return new Promise(function(resolve, reject){ setTimeout(function() { result = x/y; if(!isFinite(result)) { reject(result); } else { resolve(result); } }, time); }); } /*now define the calculator using promise*/ function divide(x,y, time){ calculateDivision(x,y, time).then(function(result){ console.log("success:" + result); }, function(reason){ console.log("error: " + reason); }); } /*results will come inverted cause of time to calculate*/ divide(9,3, 2000); //divide 9 by 3 after 2 seconds divide(1,0, 1000); //divide 1 by 0 after 1 second divide(1000, 2, 500); //divide 1000 by 2 after 500 miliseconds
运行此脚本,您将看到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.