How to Make a JavaScript Promise Return a Value – JavaScript Guide

javascript

I have a spec from a client for an implementation of a method in a module:

 // getGenres():
 //  Returns a promise. When it resolves, it returns an array.

If given an array of genres,

['comedy', 'drama', 'action']

Here is a skeleton method with a promise:

MovieLibrary.getGenres = function() {
  var promise = new Promise(function(resolve, reject) {
    /* missing implementation */
  });

  return promise;
};

Can the promise be made to return the data found in the genres? Is there a better way to achieve the spec description?

Best Answer

It sounds like you aren't understanding how promises are used. You return a promise. Then, later when your code resolves the promise, it resolves it with a result and that result is passed to the .then() handler attached to the promise:

MovieLibrary.getGenres = function() {
  var promise = new Promise(function(resolve, reject) {
    /* missing implementation */
    resolve(result);
  });

  return promise;
};

MovieLibrary.getGenres().then(function(result) {
    // you can access the result from the promise here
});