javascript Promise

Published on:


  • Read this introduction first
  • Return a resolved Promise return Promise.resolve(VALUE)
  • Return a rejected Promise return Promise.reject(VALUE)
  • in each then or catch, the spec requires you to return a promise. If you throw an error in then/catch block, it is treated as returning a rejected promise. If you return a constant, it is treated as returning a resolved promise.
    • if you didn't return anything, an undefined is returned, which is resolved promise.
  • catch(function (error) {...}) equals to then(undefined, function (error) {...})

Retry Multiple times

Assume you have a function which will return resolved/rejected promise with equal probability. We want to retry if failed for 10 times. From the spec, we knows

  • if in a then, it got a resolved promised but resolved handler is undefined, this promise will be passed to next then
  • if in a then, it got a rejected promised but rejected handler is undefined, this promise will be passed to next then

so to achieve retry, you could write like this

return fn()
  .catch(function () {
    return fn();
  .catch(function () {
    return fn();
  .catch(function () {
    return fn();

If first fn() return a resolved promise, it will pass through all the following then (catch is then without resolved promise handler) blocks, which it only resolved once and return.

If first fn() return a rejected promise, it will go to first catch, and in it we return a new fn() promise, which equals to retry once.

Flatten nested

var final = promise1.then(function (result1) {
  return getPromise2(result1).then(function (result2) {   - (1)
    // handle result 2                                    - (2)

    return result2
  }, function (error2) {
    // handle error2

}).catch(function (error1) {                              - (3)
    // handle error1


could be rewritten as

var final = promise1.then(function (result1) {
  return getPromise2(result1);                        - (1)
}).then(function (result2) {
  // handle result 2

  return result2;                                     - (2)
}).catch(function (error) {
  // error may be error 1 or error 2

  // need to test it


In first snippet, if you run to line (2), because there is no resolved promised handler in the following then block, result2 will be return by (1). And since line (3) doesn't handle resolved promise, result2 will go to final.

In second snippet, line (2) return will go to final as well for the same reason.



comments powered by Disqus