How do I make a javascript return value from promise?

527    Asked by PeterWilkins in Java , Asked on Oct 13, 2022

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?


Answered by Phil Wilson

It sounds like you aren't understanding how promises are used. You return value from 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
});


Your Answer

Interviews

Parent Categories