如何实现类似jquery的'success'和'failure'函数来链接回调

时间:2022-02-02 14:30:26

I am new to javascript and I need to chain functions execution, but function to react on success and failure different. Array of functions is get as parameter and result from previous is input parameter for next in chain in case of success, in error case I can define some alert/log behavior. I like how jquery has for exampel for GET ajax method success and failure. How to make that inner function fire those events, how is this implemented in javascript ?

我是javascript的新手,我需要链接函数执行,但函数对成功和失败的反应不同。函数数组是作为参数得到的,前面的结果是成功时下一个链的输入参数,在错误情况下我可以定义一些警报/日志行为。我喜欢jquery如何获得GET ajax方法的成功和失败。如何使内部函数触发那些事件,如何在javascript中实现?

1 个解决方案

#1


8  

Live demo of both solutions here (click).

这里有两个解决方案的现场演示(点击)。

Promises are now considered to be the best approach, rather than callbacks. I'll start with callbacks because they are easier to get started with and talk about promises afterwards.

承诺现在被认为是最好的方法,而不是回调。我将从回调开始,因为他们更容易开始并在之后谈论承诺。

Basic callbacks with object parameters:

//change this to true or false to make the function "succeed" or "fail"
//var flag = false;
var flag = true;

//this is the function that uses "success" and "error"
function foo(params) {
  //some condition to determine success or failure
  if (flag) {
    //call the success function from the passed in object
    params.success();
  }
  else {
    //call the error function from the passed in object
    params.error();
  }
}

//function "foo" is called, passing in an object with success and error functions
foo({
  success: function() {
    console.log('success!');
  },
  error: function() {
    console.log('error!');
  }
});

Make sure a callback was passed in before firing it:

For a complete solution, you would also want to make sure those properties exist before calling them - only call the success and error functions if they were passed in.

对于完整的解决方案,您还需要在调用它们之前确保这些属性存在 - 只有在传入成功和错误函数时才调用它们。

Here's how I would do that:

这是我将如何做到这一点:

if (flag) {
  //the function is only fired if it exists
  params.success && params.success();
}

Callbacks passed in as individual parameters:

You don't have to pass them in an object. You could just have the function accept individual parameters:

您不必在对象中传递它们。您可以让函数接受单个参数:

function foo(success, error) {
  if (flag) {
    success && success();
  }
  else {
    error && error();
  }
}

foo(
  function() {
    console.log('success!');
  }, 
  function() {
    console.log('error!');
  }
);

Callbacks passed in individually or in an object:

You can also have the function use individual parameters or functions from an object based on what was passed in. You would just check whether the first parameter is a function or object and use it accordingly:

您还可以让函数根据传入的内容使用对象中的单个参数或函数。您只需检查第一个参数是函数还是对象并相应地使用它:

function foo(success, error) {
  if (arguments.length === 1 && typeof arguments[0] === 'object') {
    var params = arguments[0];
    success = params.success;
    error = params.error;
  }
  if(flag) {
    success && success();
  }
  else {
    error && error();
  }
}

foo(function() {
  console.log('success');
});

foo({
  success: function() {
    console.log('success!');
  }
});

Promises! Huzzah!

As I said, I greatly prefer to use promises, which are very nice for dealing with asynchronous functions. This will require a promise library or ES6 JavaScript. This is how it looks with jQuery. Most libraries are similar:

正如我所说的,我更喜欢使用promises,它非常适合处理异步函数。这将需要一个promise库或ES6 JavaScript。这就是jQuery的外观。大多数库类似:

function bar() {
  var deferred = new $.Deferred();

  if (flag) {
    //if you resolve then, the first "then" function will fire
    deferred.resolve();
  }
  else {
    //if you reject it, the second "then" function will fire
    deferred.reject();
  }

  return deferred.promise();
}

//since "bar" returns a promise, you can attach a "then" function to it
//the first function will fire when the promise is resolved
//the second function will fire when the promise is rejected
bar().then(function() {
  console.log('bar success!'); 
}, 
function() {
  console.log('bar error!');
});

With JavaScript ES6 Promise:

使用JavaScript ES6承诺:

function bar() {
  return new Promise(function(resolve, reject) {
    if (flag) {
      resolve()
    }
    else {
      reject();
    }
  })
}

Promises can be difficult to understand at first. There are plenty of good tutorials around to help you wrap your head around them.

承诺起初可能难以理解。有很多很好的教程可以帮助你绕过它们。

#1


8  

Live demo of both solutions here (click).

这里有两个解决方案的现场演示(点击)。

Promises are now considered to be the best approach, rather than callbacks. I'll start with callbacks because they are easier to get started with and talk about promises afterwards.

承诺现在被认为是最好的方法,而不是回调。我将从回调开始,因为他们更容易开始并在之后谈论承诺。

Basic callbacks with object parameters:

//change this to true or false to make the function "succeed" or "fail"
//var flag = false;
var flag = true;

//this is the function that uses "success" and "error"
function foo(params) {
  //some condition to determine success or failure
  if (flag) {
    //call the success function from the passed in object
    params.success();
  }
  else {
    //call the error function from the passed in object
    params.error();
  }
}

//function "foo" is called, passing in an object with success and error functions
foo({
  success: function() {
    console.log('success!');
  },
  error: function() {
    console.log('error!');
  }
});

Make sure a callback was passed in before firing it:

For a complete solution, you would also want to make sure those properties exist before calling them - only call the success and error functions if they were passed in.

对于完整的解决方案,您还需要在调用它们之前确保这些属性存在 - 只有在传入成功和错误函数时才调用它们。

Here's how I would do that:

这是我将如何做到这一点:

if (flag) {
  //the function is only fired if it exists
  params.success && params.success();
}

Callbacks passed in as individual parameters:

You don't have to pass them in an object. You could just have the function accept individual parameters:

您不必在对象中传递它们。您可以让函数接受单个参数:

function foo(success, error) {
  if (flag) {
    success && success();
  }
  else {
    error && error();
  }
}

foo(
  function() {
    console.log('success!');
  }, 
  function() {
    console.log('error!');
  }
);

Callbacks passed in individually or in an object:

You can also have the function use individual parameters or functions from an object based on what was passed in. You would just check whether the first parameter is a function or object and use it accordingly:

您还可以让函数根据传入的内容使用对象中的单个参数或函数。您只需检查第一个参数是函数还是对象并相应地使用它:

function foo(success, error) {
  if (arguments.length === 1 && typeof arguments[0] === 'object') {
    var params = arguments[0];
    success = params.success;
    error = params.error;
  }
  if(flag) {
    success && success();
  }
  else {
    error && error();
  }
}

foo(function() {
  console.log('success');
});

foo({
  success: function() {
    console.log('success!');
  }
});

Promises! Huzzah!

As I said, I greatly prefer to use promises, which are very nice for dealing with asynchronous functions. This will require a promise library or ES6 JavaScript. This is how it looks with jQuery. Most libraries are similar:

正如我所说的,我更喜欢使用promises,它非常适合处理异步函数。这将需要一个promise库或ES6 JavaScript。这就是jQuery的外观。大多数库类似:

function bar() {
  var deferred = new $.Deferred();

  if (flag) {
    //if you resolve then, the first "then" function will fire
    deferred.resolve();
  }
  else {
    //if you reject it, the second "then" function will fire
    deferred.reject();
  }

  return deferred.promise();
}

//since "bar" returns a promise, you can attach a "then" function to it
//the first function will fire when the promise is resolved
//the second function will fire when the promise is rejected
bar().then(function() {
  console.log('bar success!'); 
}, 
function() {
  console.log('bar error!');
});

With JavaScript ES6 Promise:

使用JavaScript ES6承诺:

function bar() {
  return new Promise(function(resolve, reject) {
    if (flag) {
      resolve()
    }
    else {
      reject();
    }
  })
}

Promises can be difficult to understand at first. There are plenty of good tutorials around to help you wrap your head around them.

承诺起初可能难以理解。有很多很好的教程可以帮助你绕过它们。