简体   繁体   中英

Chaining Promises Together in JavaScript

I'm working to get my head around promises in JavaScript. From my understanding, I can chain them together. However, there is something that I feel I am missing. Currently, I have an AngularJS app that is using the $localForage module . I need to set an item in local storage. Then, I need to remove an item from local storage. Finally, I need to redirect the user to another page. In an attempt to accomplish this, I've written the following code:

$localForage.setItem('name', 'John Doe')
  .then(function() { return $localForage.removeItem('history'); })
  .then(function() {
    console.log('redirecting the user...');
    $location.url('/views/page-2');
    console.log('should redirect');
  })
;

When this code executes, I see the following in the console:

redirecting the user...
should redirect

However, I never get redirected to /views/page-2 . Interestingly, if I place the $location.url('/views/page-2'); in the first then(...) , I get redirected. For that reason, I feel like there is something that I do not understand about promises.

Am I chaining together properly? Or, am I trying something that I cannot do? If I cannot do this, what is the alternative?

Thank you!

Yeah, the key thing to do is remember to add an error handler in the promise chain. This is accomplished by either adding the second-method callback to the end of your chain as Chris suggested, or ending your chain with a .catch(function(err){console.log(err);}) call.

Errors in a promise chain tend to go into the bitbucket unless you explicitly capture them.

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