setTimeout不能与node.js一起使用

use*_*712 7 javascript settimeout node.js

我正在编写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
    .....
    ......
 };
  });
Run Code Online (Sandbox Code Playgroud)

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

任何帮助表示赞赏.

谢谢

Chr*_*ris 11

你的回叫是立即执行的,因为你正在那里召唤它.

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

**编辑**

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

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

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

  • 那些应该,setTimeout排队异步代码以便稍后运行.setTimeout将立即对该代码进行排队,以便稍后运行,然后转到下一个console.log.尝试在`function(){getPC(lapetus,pc_id);中移动你的"ok ..."代码; }` (2认同)