简单运用Middleware架构编程小程序并显示运行结果
时间: 2024-01-03 21:05:35 浏览: 23
以下是一个简单的使用 Middleware 架构编程的小程序,实现了一个简单的计算器,可以在控制台中打印出计算结果:
```javascript
const add = (a, b, next) => {
const result = a + b;
console.log(`Addition result: ${result}`);
next(result);
}
const multiply = (a, b, next) => {
const result = a * b;
console.log(`Multiplication result: ${result}`);
next(result);
}
const divide = (a, b, next) => {
const result = a / b;
console.log(`Division result: ${result}`);
next(result);
}
const calculator = (a, b, operation) => {
const operations = {
'add': add,
'multiply': multiply,
'divide': divide
};
operations[operation](a, b, result => {
console.log(`Final result: ${result}`);
});
}
calculator(2, 3, 'add');
```
将上述代码保存为 `app.js` 文件,并在终端中输入以下命令运行:
```
node app.js
```
可以看到类似如下的输出:
```
Addition result: 5
Final result: 5
```
这表示中间件函数成功地拦截并处理了计算请求,并打印出了计算结果。可以尝试修改 `calculator` 函数的参数,计算不同的数学操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)