简体   繁体   中英

jquery cannot get $.when to work when waiting for promises to resolve

I have a situation that is driving me crazy because I can't seem to get it to play out properly. I have a situation where there options to fill out a total of 3 forms. However, 2 don't always ned to be filled out, only one has to be filled out. The problem is the main form that has to be filled out needs to wait if either of the other forms is filled because it needs to store their Id's as a lookup in the main form before saving. This should be relatively simple, but I have tried pretty much everything and cannot get $.when to work properly to wait for the promises to resolve.

I have a service where I call a function postItem, which is an $ajax post call

I am following this exactly, but it doesn't work:

https://dzone.com/articles/promises-and-deferred-objects

var promise1, promise2;
var promise_array = [];

if(vm.receivables) {
 promise1 = user.postDealItem(args....).then(function(response) {
           vm.model.recId = response.Id;
           return response
});
}

if(vm.standard) {
 promise2 = user.postDealItem(args...).then(function(response) {
           vm.model.stdId = response.Id;
           return response
});
}

if(promise1 != null) promise_array.push(promise1);
if(promise2 != null) promise_array.push(promise2);

$.when.apply($,promise_array).done(function(response) {
    //never gets to this point
});

Before the other 2 forms were needed, I had a single form which would complete and then once that completed I had several other sublists that were saved and it worked without issue by chaining the promises...

Now it goes past the $.when part of the code, hits the end of the block and then goes into a bunch of angular functions, and then tracedigest++ and then somewhere in there it errors out and reloads the main page. I am testing this only running one other form and that initial form does save properly, the promise just doesn't resolve properly...

Any help would be greatly appreciated, I am at my wits end as to why this isn't working as it appears it should be fine the way it is...

It looks to me like you're just missing the () after postDealItem. Change the two places where it says user.postDealItem.then(function(response) { to user.postDealItem().then(function(response) { .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM