How do I make a JavaScript promise return something other than a promise?

  • 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?

    Promises don't "return" values, they pass them to a callback (which you supply with .then()). The spec simply sounds confused to me. It's probably trying to say that you're supposed to do `resolve([genre1, genre2, ...]);` inside the promise implementation.

  • jfriend00

    jfriend00 Correct answer

    5 years ago

    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
    });
    

    This confirms that promises work the way that I expected.

    Probably, you don't understand why this might be needed. In environment, like React Native with Redux with Realm, I have to put initial state to Redux createStore. It should be fetched from Realm, but it returns promise. I just want to block until it returns data as this should be very fast and simple. Instead I get problems how to combine Realm promises and usual JSON object for createStore()

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM