gpt4 book ai didi

node.js - 使用事件驱动架构 Node js 创建 Restful api?

转载 作者:太空宇宙 更新时间:2023-11-03 22:09:09 25 4
gpt4 key购买 nike

嗨,我是 nodejs 的新手,就我而言,nodejs事件驱动,这是一个强大的功能它。

我最近几天一直在学习nodejs,并尝试使用mongodb在其中构建restful api,但我无法使用它的事件下面的 api 中的 -driven 架构是我的 sudo 代码

//routes

app.get('/someUrl', SomeClass.executeSomeController);


//controller

class SomeClass {
async executeSomeController(req, res){
let response = awaitSomeHelper.executeQueryAndBusinessLogic(req.body);
res.send(response)
}

}

根据我的理解,我已经编写了正常的代码,就像我以前使用RorPHP编写的那样,我发现的唯一区别是 Controller 正在运行异步,这在RorPhp中不会发生。

如何使用事件驱动架构来构建restful api

最佳答案

希望我能回答你的问题。基本上在某些情况下,“事件驱动架构”术语可以有不同的解释。在一种情况下,它是解释所有异步函数的基本核心 NodeJS 流程。在另一种情况下,问题的根源可能与事件、事件发射器等有关。

但主要思想是您必须等待所有异步操作。为了避免线程阻塞,它会更进一步并处理其余代码,而无需等待大量请求。我们必须知道如何处理这个异步功能。

基本异步流程

据我了解,您有与 NodeJS 中的异步操作相关的问题。这是该技术的根源——所有繁重的操作都将异步处理。这都是关于 V8 和事件循环的。

因此,为了使用异步操作,您可以使用回调函数、promise 或 async-await 语法。

回调函数

function asyncFunction(params, callback) {
//do async stuff
callback(err, result);
}

function callbackFunction(err, result) {

}

asyncFunction(params, callbackFunction);

promise

promiseFunction()
.then(anotherPromiseFunction)
.then((result) => {
//handle result
})
.catch((err) => {
//handle error
});

异步等待

function anotherAsyncFunction() {
//do async stuff
}

const asycnFunction = async (params) => {
const result = await anotherAsyncFunction();
return result;
};

事件/事件发射器

const fs = require('fs');

const filePath = './path/to/your/file';
const stream = fs.createReadStream(filePath);

stream.on('data', (data) => {
//do something
});

stream.on('end', () => {
//do something;
});

stream.on('error', (err) => {
//do something;
});

您可以根据情况和您的需求来使用这些方法。我建议跳过回调函数,因为我们有现代的异步流程工作方式(promises 和 async-await)。顺便说一句,“async-await”也返回 promise 。

这是一个简单的 Express JS 服务器示例(相当旧的语法),但仍然有效。请随时检查并写下问题:

https://github.com/roman-sachenko/express-entity-based

以下是我向您推荐的文章列表:

https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/ https://blog.risingstack.com/mastering-async-await-in-nodejs/

关于node.js - 使用事件驱动架构 Node js 创建 Restful api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47653494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com