javascript - Avoid function to return before Promise ends -
inside function have this
function() { var user = new models.commerceuser(); var userpromise = user.fetch(); userpromise .done(function() { console.log('user fetched') var commercecollection = new models.commercecollection(); var commercepromise = commercecollection.fetch({ data: { nocursor: true } }); commercepromise .done(function() { console.log('commerces fetched') var activeofferscollection = new models.activeofferscollection(); var activeofferspromise = activeofferscollection.fetch(); activeofferspromise .done(function() { console.log('activeoffers fetched') initvariables(); }) .error(function() { console.error('error while getting commerces') }); }) .error(function() { console.error('error while getting commerce') }) }) return result; }
i don't want return before callbacks have finished, don't know how it.
for asking... these backbone models , that's why have promises :)
thanks in advance
you don't have option that. operations invoke asynchronous, if own code depends on results cannot work in synchronous manner.
without taking account return result
(what do? there no result
defined anywhere!), should restructure code pipeline. start contents of function:
userpromise .done(function() { console.log('user fetched') var commercecollection = new models.commercecollection(); var commercepromise = commercecollection.fetch({ data: { nocursor: true } }); commercepromise .done(function() { console.log('commerces fetched') var activeofferscollection = new models.activeofferscollection(); var activeofferspromise = activeofferscollection.fetch(); activeofferspromise .done(function() { console.log('activeoffers fetched') initvariables(); }) .error(function() { console.error('error while getting commerces') }); }) .error(function() { console.error('error while getting commerce') }) })
instead of waiting each promise complete , schedule next step (there 3 levels of doing here), compose pipeline then
:
// error checking elided return new models.commerceuser().fetch() .then(function() { return new models.commercecollection().fetch(...); }) .then(function() { return new models.activeofferscollection.fetch(...); }) .then(initvariables);
returning new composed promise function , further chain code it.
Comments
Post a Comment