nodejs app中的间隔?

时间:2016-02-18 04:44:30

标签: javascript node.js nonblocking data-synchronization

我是新手,我尝试创建nodejs应用程序(使用mongo数据库)。我有间隔功能的问题。例如:

在severside: 我有代码的和平:

var test = setInterval(function(){
               getData()
           },1000);
var getData = function(){
   // get data from database then return to client
}

问题是我在getData完成时如何控制然后执行下一个间隔。因为我知道javascript是非阻塞所以interval和getData函数在不同的线程中,对吧?

任何人都有解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以使用setTimeout而不是setInterval:

function getData(){
   // get data from database then return to client
   setTimeout(getData, 1000);
}

getData();

答案 1 :(得分:0)

我在node.js app中做了类似的事情:

let _ = require('lodash');

function getData() {

    let previousResponse;

    let run = function() {

        let currentResponse = someMethodToGetDataFromDb();

        //Only send data to client if something has actually changed
        if(!_.isEqual(previousResponse, currentResponse)) {
            previousResponse = currentResponse;
            sendDataToClient(currentResponse);

            //This calls itself but ensures there is only ever one call to
            //the db at one time.
            setTimeout(run, 3000); 
        }

    };

    run();
}