简体   繁体   English

我们如何使用异步,以及nodeJS的最佳方法是什么

[英]How do we use Async, and what is the best way in nodeJS

I'm trying to pass a query to my database, then send the result to my client side, but it looks like the request is async, because my request happens after that my post request returns the value. 我正在尝试将查询传递到数据库,然后将结果发送到客户端,但是看起来请求是异步的,因为我的请求发生在发布请求返回值之后。

How do I set an await for request? 如何设置等待请求?

My database connection 我的数据库连接

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'my_password',
    database: 'MEETME'
});

connection.connect(function(err) {
    if (err) {
        console.log("error while connecting to database");
        console.log(err.code);
    }
});

// function that query database <-------

function queryDatabase(userQuery) {
    connection.query(userQuery, function(err, result) {
        if (err) {
            throw err;
        }
        console.log("before");
        return result;
    });
}

and this is my post request 这是我的帖子请求

//POST
app.post('/signin', function(request, response) {
    var query = queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});

the result in the console is: 控制台中的结果是:

undefined
after
before

Change the implementation of queryDatabase function to return a promise. 更改queryDatabase函数的实现以返回承诺。 Any function that returns a promise can be awaited. 可以等待任何返回诺言的函数。

function queryDatabase(userQuery){
     return new Promise((resolve,reject) => {
        connection.query(userQuery, function(err, result){
            if(err){
              reject(err);
            }
            console.log("before");
            resolve(result);
        }); 
     }); 
}



app.post('/signin', async function(request, response){
    var query = await queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});

Welcome to Node.js where everything is intended to be asynchronous and unless you explicitly structure your code in a way that cascades one event to another there's no obligation on the part of the code to run in any particular order at all. 欢迎使用Node.js,这里的所有内容都是异步的,除非您以将一个事件级联到另一个事件的方式显式构造代码,否则代码部分没有义务以任何特定顺序运行。

I'd strongly recommend picking up on Promises as a way of organizing code if you're not familiar with this concept. 如果您不熟悉此概念,我强烈建议您选择Promises作为组织代码的一种方式。 This wraps up a lot of tricky programming into some neat, tidy methods, and makes chaining, fan-out and fan-in actually pretty simple. 这将许多棘手的程序包装成一些整洁的方法,并使链接,扇出和扇入实际上非常简单。

For example, rewritten with Sequelize , a database layer that uses promises: 例如,用Sequelize重写,该数据库层使用promises:

function queryDatabase(userQuery){
   console.log("before");

   return connection.query(userQuery);
}

You return the promise, and that's used to chain. 退还诺言,该诺言已被链接起来。 If you don't you must accept a callback argument and chain that through. 如果不这样做,则必须接受回调参数并将其链接在一起。 Return values are largely ignored: 返回值在很大程度上被忽略:

function queryDatabase(userQuery, cb){
   connection.query(userQuery, function(err, result){
      cb(err, result);
   });
   console.log("before");
}

You can see there's a lot more cruft already, and even more if you needed to build off of that. 您可以看到已经有更多的废纸if,如果需要在此基础上增加更多的废纸cru。 Inserting optional steps in callback driven code is tricky . 在回调驱动的代码中插入可选步骤很棘手

Promises make your code end up looking like this: 承诺使您的代码最终看起来像这样:

app.post('/signin', function(request, response){
  queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3")
    .then(function(results) {
      console.log(results);
      console.log("after");
      response.end(query, 200);
    });
});

It's also trivial to patch in error handling in one place with catch to handle errors. 在一处修补错误并用catch来处理错误也很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Firebase 的 onAuthStateChanged() 中使用 async/await 的最佳方法是什么? - What is the best way to use async/await inside onAuthStateChanged() of Firebase? 我们如何使用生成器以同步方式编写异步代码? - How can we use generators to write async code in a sync way? NodeJs - 未定义回调 - 如何使用异步进行密码散列? - NodeJs - callback is not defined - How do I use async for password hashing? 如何在 nodejs 中使用异步等待 - How to use async await in nodejs 在蓝鸟中使用“ .then”链接异步功能。 什么是最好的方法? - Chaining async functions in bluebird with “.then”. What is the best way? 在 Vue 中保存异步数据的最佳方法是什么? - What is the best way to save async data in Vue? 解决异步任务的最佳方法是什么? - What's the best way to resolve async tasks? 在nodejs中运行单独线程的最佳方法是什么? - What is the best way to run separate thread in nodejs? NodeJS NPM soap - 如何在没有回调的情况下链接异步方法(即使用异步或承诺)? - NodeJS NPM soap - how do I chain async methods without callbacks (ie use async or Promise)? 将 React 连接到 Nodejs 后端的最佳方式是什么 - What is best way to connect React to Nodejs backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM