首页 > 解决方案 > 计算器功能的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

谢谢!

标签: javascriptasynchronousmocha.js

解决方案


你的代码有点乱,但我给你一个例子,使用你的代码,关于如何为一个计算器功能做一个承诺。

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

运行这个脚本,你会看到


推荐阅读