How to declare a callback, for example, Parse?

I usually declare a function with success and refuse callbacks as follows

function yoyoyo(param, successCallback, failCallback) {
  // do something with param
  // ...
  if (success) {
    successCallback('success');
  } else {
    failCallback('fail');
  }
}

then I will use it like this:

yoyoyo('abc', function(success) {
  console.log(success);
}, function(err) {
  console.log(err);  
});

BUT , when I look in the Parse Javascript Guide, they help me use a function like this (like merging success and fault tolerance in one object?)

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
  success: function(gameScore) {
    // The object was retrieved successfully.
  },
  error: function(object, error) {
    // The object was not retrieved successfully.
    // error is a Parse.Error with an error code and message.
  }
});

How can I declare my function successfully and call callbacks such as parsing?

+4
source share
3 answers

You would simply change your function to accept the callbacks argument (name it whatever you want), and then access the handlers from this object:

function yoyoyo(param, callbacks) {
  // do something with param
  // ...
  if (success) {
    callbacks.success('success');
  } else {
    callbacks.error('fail');
  }
}

then you would call it with:

yoyoyo('abc', {
    success: function(status) { 
    },
    error: function(status) {
    }
});

, , , .

+6

, . :

var parameters = {success:function() {}, error:function(){}};

:

function yoyoyo(param, callbacks) {
   //Add some error checking to check the callbacks is in the right state      
   if (typeof callbacks.success != "undefined" && typeof callbacks.error!= "undefined")
   {

       // do something with param
       // ...
       if (success) {
          callbacks.success('success');
       } else {
          callbacks.error('fail');
       }
  }
  else {
     throw "callbacks must contain a success and error method";
  }
}

:

.yoyoto(param, {success:function() {}, error:function(){}});
+2

, , , success error

​​

function (param, callbacks) {
  // do something with param
  // ...
  if (success) {
    if(callbacks && callbacks.success) callbacks.success('success');
  } else {
    if(callbacks && callbacks.fail) callbacks.fail('fail');
  }
}

, , node.js, , /apis node.

+1

Source: https://habr.com/ru/post/1622772/


All Articles