node.js - The array object returned empty when there are values assigned to it - Javascript -


while building project using tumblr api,

var latest = []; client.posts('xxxxxx', function (err, blog) {     (var = 0; <      blog.posts.length; i++) {         var post = blog.posts[i];         // condition used identify if blog post dated no later 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 variable stores blog post object satisfy condition. when uncomment console.log(post), command line prints post object 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, console.log(latest), command line prints []. why latest returning empty array here?

as pointed out in comments, client.posts() asynchronous method, not going work sequentially you're expecting to.

var latest = []; client.posts('xxxxxx', function (err, blog) {     // not reached until after hear api     // , latest has been logged. });  console.log(latest) 

if want wait print until you've heard api, you're going need use asynchronous programming methods promises or add functionality want inside of client.posts callback.

this print properly:

var latest = []; client.posts('xxxxxx', function (err, blog) {     (var = 0; < 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 loop completes }); 

Comments