计算器功能的JavaScript承诺

时间:2019-01-23 17:44:56

标签: javascript asynchronous mocha

曾经试图解决这个编码挑战,但我遇到了麻烦。要么让我头疼,要么我只是想念一些明显的东西。下面是到目前为止我要尝试创建的函数所需的代码以及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();

Calculator类用于其他测试。我在计算功能上遇到麻烦,无法通过底部的测试。有什么想法或见解吗?

**这是我得到的错误-错误:超时超过2000毫秒。对于异步测试和挂钩,请确保调用了“ done()”;如果返回承诺,请确保其解决。https://cdnjs.cloudflare.com/ajax/libs/mocha/4.0.1/mocha.min.js:1:38622

谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码有点混乱,但是我使用您的代码为您提供了一个示例,说明如何对计算器功能做出承诺。

promise函数必须始终包装异步函数。然后,相应地调用resolvereject,看看是否有错误。

/* 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

运行此脚本,您会看到