我试图两次运行函数,但两次都传递不同的参数。
尽管我认为正确的参数是在正确的时间传递的,但有时我的变量会更新,我不确定何时或为什么。
这里是我稍微简化的js:
// randomFilter
const postContent = $('.posts');
const limit = 1;
let index = 0;
let tag;
const retrievePosts = () => {
const protocol = document.location.protocol;
const baseURL = 'api.tumblr.com/v2/blog/';
const blog = 'studio-lukeharby.tumblr.com';
if (index === 0) {
tag = 'cubes';
} else if (index === 1) {
tag = 'objects';
}
console.log('index at start:', index);
$.ajax({
type: 'GET',
url: `${protocol}//${baseURL}${blog}/posts`,
dataType: 'jsonp',
data: {
api_key: sw._site.tumblrAPIKey,
tag: tag
},
success: function(data){
let randomNumber;
randomNumber = Math.floor(Math.random() * data.response.total_posts);
console.log(`1st api call tag: ${tag}`);
$.ajax({
type: 'GET',
url: `${protocol}//${baseURL}${blog}/posts`,
dataType: 'jsonp',
data: {
api_key: sw._site.tumblrAPIKey,
offset: randomNumber,
tag: tag,
limit: limit
},
success: function(data) {
postContent.append(`<li><img src='${data.response.posts[0].photos[0].original_size.url}' alt='[${data.response.posts[0].tags}]' /></li>`);
setImgProps();
setWrapperProps();
console.log('randomNumber:', randomNumber, 'posts:', data.response.total_posts);
console.log(`2nd api call tag: ${tag}`);
}
});
},
error: function(error){
pageWrapper.empty();
pageWrapper.append('<p class="content errorInfo">Sorry there was an issue retrieving the data</p>');
postContent.remove();
elem.removeClass(loadingClass);
console.log(error.statusText);
},
complete: function() {
}
});
}
const initCounter = () => {
while (index < 2) {
index++
retrievePosts();
console.log('index:', index, 'tag:', tag);
}
};
postContent.empty();
initCounter();
我有一个有效的示例jsfiddle
理论上,该函数应查找标记为'cubes'
的帖子,并检查带有该标签的帖子总数,然后随机返回其中的1个帖子。然后,它应该通过下一个标签,检查帖子总数,然后通过offset参数返回一个随机的帖子。因此,从理论上讲,每个周期都应始终返回一个帖子。
HALP
上面代码的问题是tag
的作用域是全局的。所以这是发生了什么:
retrievePost
函数tag
已更新,并且您的ajax调用被放入队列中,以便稍后运行]retrievePost
函数tag
已更新,并且您的ajax调用被放入队列中,以便稍后运行]tag
的相同值运行>将let tag;
放入retrievePost
函数内部,并且tag
应该正确,尽管您将无法再在initCounter
函数中进行打印。您也可以这样做:
const postContent = $('.posts');
const limit = 1;
let index = 0;
let outerTag;
const retrievePosts = () => {
const protocol = document.location.protocol;
const baseURL = 'api.tumblr.com/v2/blog/';
const blog = 'studio-lukeharby.tumblr.com';
let tag;
if (index === 0) {
tag = 'cubes';
} else if (index === 1) {
tag = 'objects';
}
outerTag = tag;
...
}
const initCounter = () => {
while (index < 2) {
index++
retrievePosts();
console.log('index:', index, 'tag:', outerTag);
}
};
问题是范围。