javascript 回调

166 阅读1分钟

回调是作为参数传递给另一个函数的函数,用于处理javascript程序异步逻辑。

在Javascript中,函数可以将函数作为参数,并且可以由其他函数进行返回。执行此操作的函数称为高阶函数,任何作为参数传递的函数都称为回调函数。

常见的回调函数包括在原生JavaScript类型的方法中使用的同步回调,如array.map、array.forEach、array.find、array.filter和array.reduce。回调地狱问题是指由于回调太多而使得代码变得杂乱无章,但可以通过将回调函数作为参数传递给高阶函数来解决这个问题。

here is an example of a higher-order function that uses a callback in JavaScript:

    function calculate(num1, num2, operation) {
      return operation(num1, num2);
    }

    function add(num1, num2) {
      return num1 + num2;
    }

    function multiply(num1, num2) {
      return num1 * num2;
    }

    console.log(calculate(2, 3, add)); // Output: 5
    console.log(calculate(2, 3, multiply)); // Output: 6

In this example, calculate is a higher-order function that takes two numbers and an operation function as arguments.

The add and multiply functions are callback functions that are passed as arguments to calculate.

calculate then invokes the callback function and returns the result.

When calculate is called with add as the callback function, it adds the two numbers and returns the result.

Similarly, when calculate is called with multiply as the callback function, it multiplies the two numbers and returns the result.