使用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是一个变量存储满足条件的任何博客帖子对象。取消注释console.log(post)时,命令行会打印post对象,如下所示:
{ 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:.......}
但是,对于console.log(最新),命令行打印[]。为什么最新在这里返回一个空数组?
答案 0 :(得分:1)
正如评论中所指出的那样,client.posts()
是一种异步方法,所以它不像你期望的那样按顺序工作。
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)
如果您想等到打印直到您从API中回复,那么您将需要使用一些异步编程方法(如promises)或在client.posts
回调中添加您想要的功能
这将正确打印:
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
});