请看一下这种方法。在这个函数响应中,我调用了两个函数findConnectedUsersRelationship()
和displayUsers(response.users)
。
问题是displayUsers(response.users)
方法运行并在findConnectedUsersRelationship()
之前获得结果。我的要求是我需要先运行findConnectedUsersRelationship()
和第二displayUsers(response.users)
。第二种方法取决于第一种方法。
function filterUsers(location, gender, youngAge, oldAge, interests){
var userId = signedUserId;
$.post(urlHolder.filter, {
userId: userId,
location: location,
gender: gender,
youngAge: youngAge,
oldAge: oldAge,
interests: interests
}, function(response) {
console.log('User response <<>>', response.users.length);
var filteredUsers;
findConnectedUsersRelationship();
displayUsers(response.users);
});
}
// To find connected user relationship
var relationshipList = new Array;
function findConnectedUsersRelationship() {
try {
$.post(urlHolder.findConnectedUsersRelationship, {
userId : signedUserId
}, function(response) {
//console.log('response downforanything: ', JSON.stringify(response));
if (response) {
for (var counter = 0; counter < response.users.length; counter++) {
relationshipList.push(response.users[counter].id);
}
} else {
console.log('No connected users >>>> ');
}
//console.log('relationshipList.length',relationshipList);
console.log('relationshipList length in auto complete *** ',relationshipList.length);
});
} catch (e) {
console.log('findConnectedUsersRelationship Exception >>>', e);
}
}
答案 0 :(得分:5)
$.post
会返回promise
。
您可以使用它来继续您的代码:
function filterUsers(location, gender, youngAge, oldAge, interests){
$.post(url, { ... }, function(response) {
findConnectedUsersRelationship().done(function() {
displayUsers(response.users);
});
});
}
并更改您的findConnectedUsersRelationship()以从其ajax函数返回promise,因此而不是:
function findConnectedUsersRelationship() {
$.post(...
它变成了
function findConnectedUsersRelationship() {
return $.post(...