我怎样才能在express node.js中设置setTimeout?

时间:2016-06-28 16:21:47

标签: javascript jquery node.js

我使用2个javascript函数从Kinvey的数据库中获取数据。我希望第一个函数被执行,下一个调用在执行前等待2秒。每次我使用setTimeout我得到: 我的错误是:

TypeError: first._onTimeout is not a function
    at Timer.listOnTimeout (timers.js:92:15)

我的代码是:

router.post('/datacol/getuserdata', (req, res) => {
  request(
    {
      url: kinveyurl + 'getPrivacyLevel',
      method: 'POST',
      json: {
        "user_id" : req.body.user,
        "sensors" : parseInt(req.body.sensor),
        "contexts": parseInt(req.body.context),
        "day_no"  : parseInt(req.body.day),
        "data_collectors": parseInt(req.user.type)
      },
      auth: {
        user: config.kinvey.appKey,
        pass: config.kinvey.masterSecret,
        sendImmediately: true
      }
    }, ( err, resp, bod) => {
    if(err) console.error(err)
    console.log("User " + req.body.user + " Summarization Level = " + bod.summarization_level)

    // This here should execute after 2 seconds!!!
    // I try to set the timeout here!!
    setTimeout(request(
      {
        url: kinveyurl + 'getAccelerometerData',
        method: 'POST',
        json: {
          "user_id" : req.body.user,
          "summarization_level": parseInt(bod.summarization_level),
          "day_no"  : parseInt(req.body.day)
        },
        auth: {
          user: config.kinvey.appKey,
          pass: config.kinvey.masterSecret,
          sendImmediately: true
        }
      }, ( err, resp, sensorData) => {
      if(err) console.error(err)
      console.log(sensorData)
      res.render('datacolaccelerometer', { user : req.user, sensordata: sensorData })
    }),3000);
  })
})

我是新来的表达,我不知道该放在哪里。 总之,我想知道我应该把setTimeout放在哪里,这样我就可以将第二次调用javascript函数的执行推迟2秒,谢谢!

1 个答案:

答案 0 :(得分:-1)

这是使用记录here

的setTimeout()的正确方法
setTimeout(yourCallbackFunctionHere, 3000);

因此,在您的情况下,使用应该像这样使用它:

setTimeout(function(){
  //your express code here
}, 3000);