简体   繁体   中英

Returning promise from function

I am using the Parse Baas library. I have some functions defined that call various Parse Cloud code functions. I currently have a basic understanding of javascript promises. One thing I am struggling with is how to handle the following

I have a custom function which I can call from other modules.

   function CustomFunction()
   {
        var GameScore = Parse.Object.extend("GameScore");
        var gameScore = new GameScore();
        gameScore.set("score", 1337);
        gamesScore.save().then(
          function(object) {
              // the object was saved.
              // What do I return from here??
        },
        function(error) {
                // saving the object failed.
                 // What do I return from here??
         });
   }

There are some cases where I would maybe want to fail inside gamesScore.save().then( function(object) {} so I don't want to do just return gamescore.save(). Now when i call the custom function it really needs to return a promise as the code contained within it is 'asynchronous'. So what do i return from inside the custom function.

   CustomFunction().then(
      function(result) {

    },
    function(error) {

    });

Since gamesScore.save() is already a promise, you can simply return it from CustomFunction

function CustomFunction() {
  ...
  return gamesScore.save();
}

Now you should be able to use CustomFunction like so

CustomFunction().then(function(data) {
  ...
}, function(err) {
  ...
});

Then .then() callback in your CustomFunction serves as a filter. If you want to alter the resolved/rejected results first, you can do that there. Otherwise, don't use .then(). Just return the .save() function

function CustomFunction()
{
    var GameScore = Parse.Object.extend("GameScore");
    var gameScore = new GameScore();
    gameScore.set("score", 1337);
    return gamesScore.save();
}

Afterwards, use the result using .done(result) or .fail(error)

CustomFunction().done(function(result){ console.log(result); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM