Tag: asynchronous

asynchronous:服务器启动后连接到MongoDB

我很想知道关于Node.jsasynchronous和MongoDB的一些事情。 如果服务器在我连接之前启动,并且我的模板或Ajax依赖于来自数据库的数据将服务(我预编译我的句柄)HTML文件失败或将我的模板/ Ajax等待连接,然后继续? 如果它的工作,我想更好地了解它是如何工作的! 如果失败了,我该如何“优雅地修复”呢? 这是一个解决scheme的例子,使用提升(对我来说似乎很糟糕): //connect to db mongodb.connect("someDBplace", (err, db)=>{ if(err){ return generalLogger.error(`The database has failed to connect: ${err}.`); }else{ //start the server now: generalLogger.info(`Connected to database: ${stringify(db.databaseName)}.`); server.listen(`${port}`, (err)=>{ if(err){ generalLogger.error(err); } //for demo: console th eMIMEtype generalLogger.info(`The Server started on port: ${port}.`); }); } });

如何用NodeJS处理这些MySQL情况

我目前正在使用MySQL数据库来开发NodeJS应用程序。 我习惯于在创build一些网站时使用PHP / MySQL,我想知道这是不是阻碍了我在开发NodeJS应用程序。 通常情况下,使用PHP / MySQL我有这种情况: 我想检索我美丽的烹饪网站的所有食谱,存储在表食谱 ,并为每个食谱,我想检索存储在表成员的作者信息 。 使用PHP / MySQL,一个可能的方法是使用MySQL JOIN,但我也喜欢这样做: /* Let's retrieve all recipes */ $recipes = $this->recipe_model->all(); /* For each recipe, let's get the author information using the author id stored in the recipe */ foreach ($recipes as $key => $recipe) { $recipes[$key]["author"] = $this->author_model->get($recipe["author"]); } 其实,我想在我的NodeJS中重现这一点,但是由于asynchronous系统,这很复杂。 我试图使用asynchronous,但我想确保这是唯一的替代我的问题。 也许我也在NodeJS中有什么错(我对这个技术没有太多的经验)。 […]

如何在Express请求处理程序中编写非阻塞asynchronous函数

所有: 我很新的节点asynchronous编程,我不知道我怎么可以写一些快速请求处理程序,可以处理耗时繁重的计算任务无块快速处理的要求? 我认为setTimeout可以做到这一点,把工作在事件循环,但它仍然阻止其他请求: var express = require('express'); var router = express.Router(); function heavy(callback){ setTimeout(callback, 1); } router.get('/', function(req, res, next) { var callback = function(req, res){ var loop = +req.query.loop; for(var i=0; i<loop; i++){ for(var j=0; j<loop; j++){} } res.send("finished task: "+Date.now()); }.bind(null, req, res); heavy(callback) }); 我猜我不明白setTimeout是如何工作的(我对setTimeout的理解是在1ms的延迟之后,它会在一个独立的线程/进程中触发callback,而不会阻塞其他重呼叫),任何人都可以告诉我怎么做,而不会阻塞其他请求重()? 谢谢

访问nodejs中的JSON对象时出错

我有一个名为“UserSessions.js”的variablesvar sessions = {} 。 我正在使用一个唯一的时间戳来维护sessions = {}中每个用户的一些信息。 我已经导出这个variables使其可用于其他文件。 当我访问主文件“app.js”中的sessions = {}时 ,一切正常。 但是,当我尝试从另一个文件'Sessiongreet.js'访问相同的variables,它会给出错误。 以下是我如何访问数据: 假设“2017-04-07T11:55:40.162Z”是仅分配一次的唯一时间戳。 在app.js中: 这工作正常: const UserSessions=require('./UserSessions.js'); sessionId='2017-04-07T11:55:40.162Z'; var data=UserSessions.sessions[sessionId].context; 在sessionGreet.js中: 这给了错误: const UserSessions=require('./UserSessions.js'); sessionId='2017-04-07T11:55:40.162Z'; var data=UserSessions.sessions[sessionId].context; 我知道UserSessions.sessions [sessionId] .context存在,因为它可以在app.js文件中访问,然后在另一个文件中访问它。 这是我得到的确切的错误: TypeError: Cannot read property '2017-04-07T11:55:40.162Z' of undefined at initSession (/media/row_hammer/sessionGreet.js:24:33) at Object.run (/media/row_hammer/sessionGreet.js:67:2) at Object.handlePostback (/media/row_hammer/sessionTemp.js:89:19) at runPostback (/media/row_hammer/app.js:113:15) at /media/row_hammer/app.js:161:3 […]

节点服务器asynchronous调用后端服务

我是Node新手,我正在写我的第一个节点服务器。 在调用后端rest服务之后,它应该通过简单的页面来获得一个简单的获取请求。 我正在使用express来pipe理请求和axios包来作出后端请求。 问题是,服务器阻塞事件循环,我有问题了解如何调用后端asynchronous。 截至目前,前端服务器一次只能pipe理一个请求! 我期望如果后端服务每次都需要10秒的时间来回答,前端服务器可以在10秒内回答两个并发请求,而不是在20秒内。 我错在哪里? 以下是前端节点代码的摘录: app.get('/', function(req, res) { //Making the call to the backend service. This should be asynchronous… axios.post(env.get("BACKEND_SERVICE"), { "user": "some kind of input"}) .then(function(response){ //do somenthing with the data returned from the backend… res.render('homepage'); }) } 这里是后端节点代码的提取: app.post('/api/getTypes', jsonParser, function (req, res) { console.log("> API request for 'api/getTypes' […]

Google Cloud Storage(Js),asynchronous/等待和云function错误

这是现在解决在GOOGLE侧 Google Cloud NodeJs库现在已经集成了修复程序。 保持这个问题仅供参考。 原文问题 我希望我的代码干净(er),并使用Typescript&async /等待编写访问Google云端存储的Cloud Functions。 我的tsconfig.json一些重要部分: { "compilerOptions": { "declaration": false, "target": "es6", "module": "commonjs", "noImplicitAny": true, "removeComments": true, "noUnusedLocals": true, "moduleResolution": "node", "sourceMap": false, "typeRoots": [ "node_modules/@types" ], "lib": [ "es2016" ], "emitDecoratorMetadata": true, "experimentalDecorators": true, "outDir": "./" } } 我遇到的第一个错误是ECONNRESET ,我正在打这样的电话,可能是这样的: await bucket.file(path).download({ destination: tempFilePath }) 我已经算出了function的其余部分没有等到这一行完成,整个function执行结束之前,文件从GCS下载到临时path。 所以我把这一节放到try / […]

使c ++插件asynchronous

我已经设法将dlibvideo跟踪器集成到我的节点应用程序中。 我现在的问题是让它不被阻塞。 任何帮助将不胜感激。 谢谢。 这是我的代码 #ifndef MYOBJECT_H #define MYOBJECT_H #include "ImageDetails.h" #include "opencv2/core/core_c.h" #include "../dlib/opencv/cv_image.h" #include "../dlib/image_processing.h" #include "../dlib/gui_widgets.h" #include "../dlib/image_io.h" #include "../dlib/dir_nav.h" #include "/home/pi/projects/lib/node-opencv-master/src/Matrix.h" #include "/home/pi/projects/lib/node-opencv-master/src/Contours.h" #include <nan.h> //#include <node_object_wrap.h> using namespace dlib; using namespace cv; using namespace std; class MyObject : public Nan::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); private: explicit MyObject(std::vector<ImageDetails> details, […]

节点asynchronous每个循环之间的延迟

我有一个对象,我正在迭代。 现在对于这个对象中的每一个键值对,我都需要调用一个可以产生a / o请求的函数,但是我需要在这些迭代之间等待。 这是函数会迭代,读取第一个对象,传递它的function,并等待n毫秒,n毫秒后它将读取第二对,传递它的function,并再次等待,直到列表中的对象结束。 我该怎么做呢? 目前这是我的代码大纲 async.forEachOfSeries(object1, function(value, key, callback) { //send switch status if(object1.key1 == some condition){ sql.query1 } some io request based on query result callback(); want some delay here }, function(err) { if( err ) { handle error } else { report success } } )

如何从需要返回语句的GraphQLparsing器中调用asynchronousnode.js函数?

graphql.org/graphql-js提供的用于创build简单GraphQL实现的Hello World示例如下: var { graphql, buildSchema } = require('graphql'); // Construct a schema, using GraphQL schema language var schema = buildSchema(` type Query { hello: String } `); // The root provides a resolver function for each API endpoint var root = { hello: () => { return 'Hello World!'; } }; // Run the […]

Async.waterfall:callback已经被调用?

我知道这是以前在这里提到的一个话题,但我使用rethinkdb async.waterfall,我得到Error: Callback was already called 。 奇怪的是,即使它抛出的错误和崩溃的应用程序,它仍然会创build我所需要的数据库和表。 我已经阅读了几个像NodeJS Async:Callback已经被调用的答案吗? 或使用async.waterfall ,但我似乎无法得到任何地方。 我的控制台也告诉我,错误是在db.js:40:9 ,但我是新来的节点,只是不知道它想要什么callback。 我究竟做错了什么? 我需要在这里嵌套callback吗? 我正在使用的代码如下所示。 任何帮助,我可以在这里非常感激,如果需要我可以张贴其他相关的代码。 多谢你们。 db.js: exports.setDatabaseAndTables = function() { async.waterfall([ function connect(callback) { r.connect(config.rethinkdb, callback); }, function createDatabase(connection, callback) { // Create the database if needed. r.dbList().contains(config.rethinkdb.db).do(function(containsDb) { return r.branch( containsDb, {created: 0}, r.dbCreate(config.rethinkdb.db) ); }).run(connection, function(err) { callback(err, connection); […]