While building a project using tumblr API,
var latest = [];
client.posts('XXXXXX', function (err, blog) {
for (var i = 0; i <
blog.posts.length; i++) {
var post = blog.posts[i];
// this condition is used to identify if any blog post is dated no later than 7 days.
if ((new Date().valueOf() - Date.parse(post.date)) /(1000*60*60*24) <= 7){ latest.push(post);
/ / console.log(post);
}
};
});
console.log(latest)
latest is a variable stores any blog post object that satisfy the condition. When uncomment console.log(post), command line prints post object like this:
{ blog_name: '......',
id: ......,
post_url: '......',
slug: '......',
type: 'text',
date: '2015-07-20 16:42:30 GMT',
timestamp: ....,
state: 'published',
format: 'html',
reblog_key: '.....',
tags: [],
short_url: '.......',
recommended_source: null,
followed: false,
highlighted: [],
liked: false,
note_count: 0,
title: '.....',
body:.......}
However, for console.log(latest), command line prints []. Why is latest returning an empty array here?
As pointed out in the comments, client.posts()
is an asynchronous method, so it is not going to work sequentially like you're expecting it to.
var latest = [];
client.posts('XXXXXX', function (err, blog) {
// This is not reached until AFTER you hear back from the API
// and latest has already been logged.
});
console.log(latest)
If you want to wait to print until you've heard back from the API, you're going to need to use some asynchronous programming methods like promises or add the functionality that you want inside of the client.posts
callback.
This will print properly:
var latest = [];
client.posts('XXXXXX', function (err, blog) {
for (var i = 0; i < blog.posts.length; i++) {
var post = blog.posts[i];
if ((new Date().valueOf() - Date.parse(post.date)) /(1000*60*60*24) <= 7){
latest.push(post);
}
}
console.log(latest); // Prints when for loop completes
});