markdownjs-回调函数(代码片段)

author author     2022-12-13     442

关键词:

# Callback Function

In JavaScript, you can pass functions as an argument to another function.

```js
const host = function(cb) 
  cb();


const callback = function () 
  console.log("You called be back from host");


host(callback); // "You called be back from host"
```

In this example, we passed the `callback` function to the `host` function.

The `cb` argument in `host` function is now the `callback` and we can call it anytime using `cb`;

**note:** This is not a fixed variable or arguments name. We can call them whatever we want.

## Why do we use a Callback Function

### Using a regular function

```js
const calc = function(operator, num1, num2) 
  if (operator === "+") 
    return num1 + num2;
  
  
  if (operator === "-") 
    return num1 - num2;
  
;

let result = calc('+', 1, 2);

console.log(result); // 3
```

Instead of providing an `operator`, we can provide a way to calculate this number.

### Using Callback Function 

```js
let add = function(a, b) 
  return a + b;


let subtract = function(a, b) 
  return a - b;


const calc = function(calcFunction, num1, num2) 
  return calcFunction(num1, num2);


let result = calc(add, 1, 2);

console.log(result); // 3
```

markdownjs同步回调和异步回调(代码片段)

查看详情

markdownjs(或任何其他语言)中更好的异步/无功功能设计-通用干扰回调(ucc)设计(代码片段)

查看详情

markdownjs:什么是函数式编程?(代码片段)

查看详情

markdownjs改变函数运行时的上下文(代码片段)

查看详情

markdownjs代码组织(代码片段)

查看详情

markdownjs-闭包(代码片段)

查看详情

markdownjs承诺(代码片段)

查看详情

markdownjs手册(代码片段)

查看详情

markdownjs高级(代码片段)

查看详情

markdownjs:将军(代码片段)

查看详情

markdownjs:吊装(代码片段)

查看详情

markdownjs承诺(代码片段)

查看详情

markdownjs:将军(代码片段)

查看详情

markdownjs:继承(代码片段)

查看详情

markdownjs集合(代码片段)

查看详情

markdownjs香草(代码片段)

查看详情

markdownjs模块(代码片段)

查看详情

markdownjs承诺(代码片段)

查看详情