javascript - Promises call their success callback too late -
i have code follows:
products.saveapplications = function (product) { var promises = []; ko.utils.arrayforeach(product.applications(), function (item) { var applicationtosend = ko.mapping.tojs(item); promises.push($.ajax({ type: "post", contenttype: "application/json", url: serviceurl + "/insertapplication", data: json.stringify(applicationtosend), success: function (data) { alert("doing success callback now."); item.id(data); }})); }); homecoming promises; }
then function products.saveenvironments
, same, except calls different function in controller, , function products.saveinstallations
, is, again, same, except needs wait environments , applications save, because has dependant info (application.id , environment.id).
now have function, calls both these functions , waits them until both have finished:
products.savechanges = function (product) { // (...) var promises = products.saveapplications(product); promises = promises.concat(products.saveenvironments(product)); $.when(promises).done(function () { alert("we shouldn't see before other message!"); products.saveinstallations(product); }); };
the problem alert box "we shouldn't see message before other message!" appears before "doing success callback now", means id properties null @ time. leads me conclusion $.when
phone call actual promises, doesn't wait success callbacks finish. how can create wait? give thanks you.
you using $.when
incorrectly. can't pass multiple promises array; if that, treats array other non-promise value , turns completed promise array of still-pending promises result. that, of course, not useful.
you need utilize .apply
instead simulate calling $.when
each promise separate argument, this:
$.when.apply(null, promises).done(function () { ... });
javascript jquery ajax promise
No comments:
Post a Comment