我是事件/回调样式编程和NodeJS的新手.我正在尝试实现一个使用node-mysql模块提供ddbb数据的小http服务器.
我的问题来自查询结构.由于经常有查询需要先前查询的结果才能运行,因此我无法同时(异步)运行所有这些查询,因此我不得不等待一些结果.
我的第一种方法是同时运行所有非依赖查询,然后循环,直到所有这些查询都设置了一个标记,说我已经完成了所以我可以继续使用依赖(同步),但我不知道这是否是正确的方法.
像这样的东西:
function x(){
var result_for_asynch_query_1 = null
var result_for_asynch_query_2 = null
mainLoop(){
// call non-dependant query 1
// call non-dependant query 2
// loop until vars are != null
// continue with queries that require data from the first ones
}
}
//for each browser request
httpServer{
call_to_x();
}.listen();
Run Code Online (Sandbox Code Playgroud)
这样我可以在最终结果中节省一些时间,因为我不会以串行方式等待所有响应,而只是等待最长的响应.
有一个共同的方法来做到这一点?我没有遵循任何设计模式?