This question already has answers here:
How do I return the response from an asynchronous call?
(36个答案)
3年前关闭。
请看看这种方法。在此函数响应中,我调用了两个函数
问题是
并更改您的findConnectedUsersRelationship()以从其ajax函数返回promise,因此,而不是:
它成为了
(36个答案)
3年前关闭。
请看看这种方法。在此函数响应中,我调用了两个函数
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);
}
}
最佳答案
$.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(...