问题
I have a jQuery function called loadPosts which accepts three parameters, skip, take and container. Skip tells the MVC Json call how many posts to skip, take indicates the number of posts to take and container is the element that the posts are written to.
function loadPosts(skip, take, container) {
$.ajax({
url: '/Ajax/LoadPosts',
type: 'POST',
dataType: 'json',
data: { skip: skip, take: take },
success: function (posts) {
if (posts == null) {
return;
}
var items = '';
$.each(posts, function (p, post) {
items += ...;
});
alert(items);
var $itemBlock = $(items);
container.append($itemBlock);
container.imagesLoaded(function () {
container.masonry('appended', $itemBlock);
});
return;
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
return;
}
});
}
This method is called twice when the page loads; first to load the most recent posts (skip = 0, take = 10) and then to load the full set of posts (skip = pageIndex * pageSize, take = pageSize).
$(document).ready(function () {
if ($('#post-container') && $('#recent-container')) {
var skip = (pageIndex * pageSize);
var take = pageSize;
var $postContainer = $('#post-container');
loadPosts(skip, take, $postContainer);
var $recentPostContainer = $('#recent-container');
loadPosts(0, 10, $recentPostContainer);
}
}
Each function in and of itself (if I comment out one of them) will work fine. It's only when I run both functions do I encounter one of two exceptions.
1. ExecuteReader requires an open and available Connection. The connection's current state is connecting.
2. There is already an open DataReader associated with this Command which must be closed first.
Here's that function
public static bool Get(int skip, int take, ListSortDirection direction, out List<Post> posts)
{
try
{
posts = Db.Posts.OrderBy(p => p.DateTimeCreated, direction).Skip(skip).Take(take).ToList();
return true;
}
catch (Exception ex)
{
posts = new List<Post>();
return false;
}
}
What I think is happening is that the second instance is starting before the first has had a chance to complete. What I want to do is find a way to wait until the first has completed before the other starts.
Any help would be greatly appreciated. Thanks!
回答1:
Return the promise that $.ajax
returns internally.
function loadPosts(skip, take, container) {
return $.ajax({ /* options left out for brevity */})
}
Can then use promise callback of first instance to initialize second
loadPosts(skip, take, $postContainer).done(function(){
loadPosts(0, 10, $recentPostContainer);
});
来源:https://stackoverflow.com/questions/35050559/first-jquery-ajax-call-collides-with-the-second