0

I am using promise chaining in which the completion of first function should start the second one.But what happens is before completing the first one the second one gets started and works.I would like to know how to start the second function based on the completion of first one.

Code in which the promise gets breaks:

LoadReviewService.saveLoad(productDetails)
    .then(LoadReviewService.saveWorker(vm.load.workers.data, vm.load, vm.smsswitch), dataFailure)
    .then(LoadReviewService.daybookWorkerDelete(vm.deleteoldworkers), dataFailure)
    .then(LoadReviewService.daybookSyncDelete(), dataFailure)
    .then(LoadReviewService.daybooksync(), dataFailure)
    .then(gotoNextPage, dataFailure);

Old code where the promise works as expected:

return LoadReviewService.saveLoad(productDetails).then(function () {
      return LoadReviewService.saveWorker(vm.load.workers.data, vm.load, vm.smsswitch);
    }).then(function () {
      return LoadReviewService.daybookWorkerDelete(vm.deleteoldworkers);
    }).then(function () {
      return LoadReviewService.daybookSyncDelete();
    }).then(function () {
      return LoadReviewService.daybooksync();
    }).then(function () {
      CommonService.hideLoader();
      gotoNextPage();
    }).then(null, function (err) {
      CommonService.handleError(err);
    });

I would like to know why the first code is breaking the promise.

Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72
  • you need to return from .then – Rahul Sharma Feb 21 '18 at 09:45
  • You have exactly the same problem that the dupetarget question has: In the "new" code, `.then(LoadReviewService.saveWorker(vm.load.workers.data, vm.load, vm.smsswitch), dataFailure)` **calls** `LoadReviewService.saveWorker(...)` and passes its return value into `then`, exactly the way `foo(bar())` *calls* `bar` and passes its return value into `foo`. You wanted to pass in a function, perhaps an arrow function: `.then(() => LoadReviewService.saveWorker(vm.load.workers.data, vm.load, vm.smsswitch), dataFailure)` – T.J. Crowder Feb 21 '18 at 09:47
  • @T.J. Crowder why should i want to use the setTimeOut in a aysnc call – Nidhin Kumar Feb 21 '18 at 09:47
  • @Nidhinkumar: See my comment above. It's not about `setTimeout`, it's about providing functions as callbacks rather than *calling* functions. Exact same problem, just a different function you're trying to pass your function into (`setTimeout` in their case, `then` in yours). – T.J. Crowder Feb 21 '18 at 09:48

0 Answers0