嗨,我是nodejs的新手,就我而言,nodejs是event-driven,这是其中一个强大的特性。
我从最近几天开始学习nodejs,并尝试用mongodb在其中构建restful,但我无法在apis中使用它的event-driven体系结构,以下是我的sudo代码
//routes
app.get('/someUrl', SomeClass.executeSomeController);
//controller
class SomeClass {
async executeSomeController(req, res){
let response = awaitSomeHelper.executeQueryAndBusinessLogic(req.body);
res.send(response)
}
}根据我的理解,我编写了正常的代码,就像我过去使用Ror或PHP编写的那样,我发现controller运行的是asynchronous,这在Ror或Php中没有发生。
如何使用event-driven体系结构来构建restful
发布于 2017-12-05 13:02:21
希望我能回答你的问题。基本上,在某些情况下,“事件驱动架构”一词可以有不同的解释。在一种情况下,它是解释所有异步函数的基本核心NodeJS流。在另一种情况下,问题的根源可能与事件、事件发射器等有关。
但是,您必须等待所有异步操作的主要想法。为了避免线程阻塞,它将进一步处理代码的其余部分,而无需等待大量的请求。在这里,我们必须知道如何处理这个异步功能。
基本异步流
据我所知,您有一些与NodeJS中的异步操作相关的问题。这是技术的根-所有繁重的操作都将被异步处理。这都是关于V8和事件循环的。
因此,为了处理异步操作,可以使用回调函数、允诺或异步等待语法。
回调函数
function asyncFunction(params, callback) {
//do async stuff
callback(err, result);
}
function callbackFunction(err, result) {
}
asyncFunction(params, callbackFunction);承诺
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;
});您可以使用这些方法取决于情况和您的需要。我建议跳过回调函数,因为我们有在异步流中工作的现代方法(承诺和异步等待)。顺便说一句,‘异步等待’返回承诺也是如此。
下面是一个简单的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/
https://stackoverflow.com/questions/47653494
复制相似问题