gpt4 book ai didi

javascript - 根据日期/时间有条件地运行代码

转载 作者:行者123 更新时间:2023-12-03 11:12:01 25 4
gpt4 key购买 nike

我正在构建一个利用 Instagram API 的基于事件的应用程序。由于该应用程序是基于事件的,我只想响应 Instagram 在特定日期和时间发送给我的回调的 Instagram API POST。我的攻击计划是将 console.log('callback hit'); 之后的所有代码包装起来有条件陈述if(current day/time <= upper bound && current day/time >= lower bound) {run code} else {console.log('event is not currently in progress')} 。我的问题是:a)这是一个合乎逻辑的方法吗? b)我将如何引用“上限/下限”和“当前日期/时间”,即如何在特定日期/时间正确编码?

下面的代码位于我的 Node “server.js”文件中:

app.post('/callback', function (req, res) {
console.log('callback hit');

//loop in all the new objects
req.body.forEach(function (data) {
console.log('received POST info');

if (data.changed_aspect !== 'media') {
console.log('not an image');
return;
}

request('https://api.instagram.com/v1/geographies/' + data.object_id + '/media/recent?client_id=' + clientID,
function (error, response, body) {
if (error) {
console.log('error');
return;
}

console.log('request sent to Instagram');
//Here we have one JSON object with all the info about the image
var image = JSON.parse(body);
console.log(image.data[0]);

//Save the new object to DB
Stadium.findOneAndUpdate( {object_id: data.object_id}, { $push: {'photos':
{ img: image.data[0].images.standard_resolution.url,
link: image.data[0].link,
username: image.data[0].user.username,
profile: image.data[0].user.profile_picture,
text: image.data[0].caption ? image.data[0].caption.text : ''
}}},
{ safe: true, upsert: false },
function(err, model) {
console.log(err);
}
);

//Send a socket to client with the new image
newImage({
img: image.data[0].images.standard_resolution.url,
link: image.data[0].link,
username: image.data[0].user.username,
profile: image.data[0].user.profile_picture,
text: image.data[0].caption ? image.data[0].caption.text : ''
});
}
);
});

res.end();

});

最佳答案

我会做这样的事情:

if (new Date('12-15-2014') <= Date.now() <= new Date('12-31-2014')) {
// your code here. i.e handleEvent();
}
else {
// nothing happens here
}

只需使用日期对象来设置日期范围。作为注释,我还建议将逻辑移动到包含方法中,只是为了稍微清理一下条件。

希望这有帮助!

关于javascript - 根据日期/时间有条件地运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27535762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com