1

I need to do a promise sequence. I'd like to use a standards based approach (ES6?). What's the best way to achieve this? getToken() and httpReq() return promises, clock.now simply returns the unix timestamp of now. My code looks something like below now (simplified/condensed). I understand I need to flatten the promise chain with a single catch... Can someone illustrate a clean, readable, non-clever, ES6 way?

// we don't have a good token so we need to get one first, then GET the resource.
getToken(host, port, auth).then(function(token) {

  httpReq(method, host, port, path, token).then(function(data) {
    console.log(data);
  }, function(status) {
    console.log(status);
  });


}, function(status) {
  console.log(status);
});
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • See also [How do you call a function with parameters in a .then function in a JavaScript promise string?](http://stackoverflow.com/questions/40538284/how-do-you-call-a-function-with-parameters-in-a-then-function-in-a-javascript-p) – guest271314 Jan 07 '17 at 23:14

1 Answers1

4

You were close. Here's how I'd do it:

getToken(host, port, auth) // Promise for token
  .then(token => httpReq(method, host, post, path, token)) // Promise for data, using token
  .then(data => console.log(data)) // final step
  .catch(err => console.error(err)); // error handling for all steps in the chain

And without the arrow functions:

getToken(host, port, auth)
  .then(function(token) { return httpReq(method, host, post, path, token); })
  .then(function(data) { return console.log(data); }) // not strictly necessary. But
                                                      // strictly equivalent to above
  .catch(function(err) { return console.log(err); });

Few things to note:

  • Don't nest .then() clauses. Instead, return a Promise from the first .then() clause, and continue the chain outside.
  • When using Promises, make sure to always return a Promise. Never leave a .then() clause without a return value, and never leave a function that has Promises without a return value.
  • Using arrow functions makes both points above easy.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308