Javascript Promises Using Class Member Resolve Reject

javascript-promises

// JavaScript - Promises - Using Promise.resolve() and Promise.reject()

Promise.resolve() and Promise.reject() are handy in situations where we need 
to create a promises that always resolve, or promises that always reject.

Promise.reject(reason): Returns a Promise object that is rejected with the given 
reason.

Promise.resolve(value): Returns a Promise object that is resolved with the 
given value. If the value is a thenable (i.e. has a then method), the returned 
promise will "follow" that thenable, adopting its eventual state; otherwise the 
returned promise will be fulfilled with the value. Generally, if you don't know 
if a value is a promise or not, Promise.resolve(value) it instead and work with 
the return value as a promise.

Sometimes, we do not need to complete an async task within the promise.  In that 
case, we can simply invoke Promise.resolve() or Promise.reject() without using 
the new keyword:

var userCache = {};

function getUserDetail(username) {
  // In both cases, cached or not, a promise will be returned

  if (userCache[username]) {
    // Return a promise without the "new" keyword
    return Promise.resolve(userCache[username]);
  }

  // Use the fetch API to get the information
  // fetch returns a promise
  return fetch('users/' + username + '.json')
    .then(function(result) {
      userCache[username] = result;
      return result;
    })
    .catch(function() {
      throw new Error('Could not find user: ' + username);
    });
}

The above code use Promise.resolve() and the fetch function, and 
in both of these cases, it always return a promise, not the user data.  
The user's data is passed to the subsequent then callback.

In the above code, only minimal stuff is done inside the function, and 
because it always return a promise, the caller of our function can do 
additional processing, or error handling by adding additional then 
callbacks or catch callbacks.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License