Date.getTime 在回调中不前进

Date.getTime not advancing in callbacks

本文关键字:回调 getTime Date      更新时间:2023-09-26

所以,我正在Node中编写一个页面抓取器,并且在一组回调中从Date.getTime获得了奇怪的行为。

function projectScrape(urlList){
        urlList.forEach(function(frag){
                request(frag.url, (function(frag){
                        return function(err, resp, body){
                                if(err) console.log('error: ' + err);
                                project$ = cheerio.load(body);
                                var tempRecord = {
                                        name: frag.name,
                                        funding: project$('span.monthly_funding_goal_percentage').text($
                                        subs: project$('span.number_of_subscribers').text(),
                                        timestamp: myDate.getTime()
                                        };
                                console.log(tempRecord);
                        }
                })(frag));
        });
};

刮擦工作正常,我从网站上获得一系列控制台转储。 但是,所有这些时间戳都是相同的。 回调显然不是同时完成的(有时回调响应之间长达几秒钟) - 那么为什么它们的时间戳为相同的毫秒?

我在这里错过了有关函数范围的一些内容吗? 在我看来,即使所有回调都引用 Date.getTime() 的相同实例,控制台转储也应该将时间戳冻结到各个回调返回时。

我能想到的唯一解释是,Date.getTime() 值是在创建回调时存储的,而不是在实际触发时更新的。

谁能在这里提供一些启示?

如果需要当前时间戳,.getTime()而不是固定日期的时间戳,请使用Date.now()。除非您以任何方式修改myDate,否则它将始终引用相同的时间和日期,因此.getTime()将始终返回相同的值:

var tempRecord = {
  name: frag.name,
  funding: project$('span.monthly_funding_goal_percentage').text(/* ... */),
  subs: project$('span.number_of_subscribers').text(),
  timestamp: Date.now() // <---------
};

不要使用 (new Date()).getTime()var myTempDate = new Date(); return myTempDate.getTime(),因为它们会创建新对象。您不需要它们,它们甚至可能会减慢您的应用程序速度(取决于 GC 实现)。