setTimeout不能与node.js一起使用

时间:2015-04-23 20:02:23

标签: javascript node.js settimeout

我正在编写mocha测试用例来测试以下步骤。我打算在调用另一个API之前进行API调用并等待30分钟。我正在使用内部节点API编写调用REST API来编写此测试用例。但由于某种原因,setTimeout不等待给定的ms。 有人可以帮助我吗?

 describe('Checkout - ', function() {
   before(function() {
     lapetus = test.Lapetus;
   });
  it('Get purchase contract after session is expired [C123]',     function(done) {
    this.timeout(180000000);
    lapetus.run(function() {
     // create customer
     ......

     // create new cart and add one item
     ......

    // create new contract with empty cart id
    .......
    var pc_id =....;

    // wait for 30 minutes for the session to expire
    console.log('wait... ' + new Date);
    this.setTimeout(getPC(lapetus,pc_id), 18000000);
    console.log('ok... ' + new Date);
    done();
  });
});

  var getPC = function(lapetus, pc_id){
   // get newly created purchase contract and verify session expired message throws
    .....
    ......
 };
  });

它不会等待30分钟。我放入的回调(getPC方法)立即执行。

感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:10)

您的回叫是立即执行的,因为您当时正在那里打电话。

将其更改为this.setTimeout(function() { getPC(lapetus,pc_id); }, 18000000);,以便您要执行的内容位于setTimeout调用的函数中。

** 修改 **

关于我的上一次评论。你应该移动你的'好吧......"你放在setTimeout里面的函数里面。这将导致" ok ..."在调用getPC之前执行。

this.setTimeout(function() {
    console.log('ok... ' + new Date);
    getPC(lapetus,pc_id)
}, 18000000);

重要的是要了解setTimeout只会启动一个计时器,以便稍后执行您的代码。 setTimeout将启动该计时器,而不是等待它完成。一旦启动该计时器,它将移动到下一位代码。