javascript - 计算器功能的javascript承诺
问题描述
一直试图解决这个编码挑战,但我碰壁了。它要么在我的头上,要么我只是错过了一些明显的东西。下面是到目前为止我得到的代码以及我试图创建函数来满足的 mocha 测试。
// 设置 Mocha 和 Chai
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. 给Calculator添加一个符合这个规范的计算函数 */
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();
Calculator 类用于不同的测试。我在使用计算功能时遇到问题,并让它通过底部的测试。有什么想法或见解吗?
** 这是我得到的错误——错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;如果返回 Promise,请确保它已解决。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
运行这个脚本,你会看到
推荐阅读
- c - Linux 中的 unistd_64.h
- c# - C# ASP.NET JQuery 脚本在部署到 IIS 10 后未加载
- php - 当我从 SMTP 发送电子邮件时,它的代码成功运行,但我没有在该电子邮件地址上收到电子邮件?
- html - 为原始 HTML 中的元素添加事件处理程序
- python - 使用 Pandas 在 Python 中打印数据帧的列标题
- c# - C# 多线程在 FOR 循环中开始和停止
- python - Nuitka 和 numpy-mkl 问题,同时构建可执行文件
- arrays - fortran 中 blas 的包装器
- c# - 在 C# 中使用 alglib 进行双线性变换的计算错误
- python - Python - 如何以一定的精度输出一个 numpy 概率数组并保持其总和