简体   繁体   English

setTimeout不能与node.js一起使用

[英]setTimeout not working with node.js

I am writing mocha test cases to test the following steps. 我正在编写mocha测试用例来测试以下步骤。 I intend to make an API call and wait for 30 minutes before calling another API. 我打算在调用另一个API之前进行API调用并等待30分钟。 I am using an internal node API which was written to call REST APIs to write this test case. 我正在使用内部节点API编写调用REST API来编写此测试用例。 But for some reason, setTimeout is not waiting for the given ms. 但由于某种原因, setTimeout不等待给定的ms。 Can someone please help me? 有人可以帮帮我吗?

 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
    .....
    ......
 };
  });

It does not wait 30 minutes. 它不会等待30分钟。 The call back I put in (the getPC method) executes immediately. 我放入的getPCgetPC方法)立即执行。

Any help is appreciated. 任何帮助表示赞赏。

Thanks 谢谢

Your call back is executing immediately because you're calling it then and there. 你的回叫是立即执行的,因为你正在那里召唤它。

Change it to this.setTimeout(function() { getPC(lapetus,pc_id); }, 18000000); 将其更改为this.setTimeout(function() { getPC(lapetus,pc_id); }, 18000000); so that what you want to execute is in a function for setTimeout to call. 所以你想要执行的是在setTimeout调用的函数中。

** Edit ** ** 编辑 **

In relation to my last comment. 关于我的上一次评论。 You should move your "ok..." inside of the function you've put inside of setTimeout . 你应该在你放入setTimeout的函数里面移动你的“ok ...”。 This will cause the "ok..." to execute right before getPC is called. 这将导致在调用getPC之前执行“ok ...”。

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

It is important to understand that setTimeout will only start a timer which will execute your code later. 重要的是要理解setTimeout只会启动一个稍后将执行代码的计时器。 setTimeout is going to start that timer, and not wait for it to finish. setTimeout将启动该计时器,而不是等待它完成。 It will move to the next bit of code once it is done starting that timer. 一旦启动该计时器,它将移动到下一位代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM