简体   繁体   English

如何在JS和Node JS中使用promise

[英]How to use promise in JS and Node JS

I have connected my sql server database to my nodejs application like this:我已将 sql 服务器数据库连接到我的 nodejs 应用程序,如下所示:

DAO.js DAO.js

const sql = require('mssql')

class DAO {
    constructor() {
        this.sqlConfig = {user: 'connexionMartin', password: 'InfoMartin', server: '192.168.102.232\\SQLEXPRESS', database: 'PROFACE'}
    }

    async connect() {
        try {
            console.log("Connecting database.....");
            let pool = await sql.connect(this.sqlConfig);
            if (pool)
                console.log("Database connected");
        } catch (err) {
            console.log(err);
        }
    }

    async getDataLastHour() {
        try {
            let result = await sql.query('SELECT * FROM PROFACE.dbo.SuiviProduction WHERE Time_Stamp >= DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0) AND DATEPART(HOUR,Time_Stamp) = DATEPART(HOUR,GETDATE())-1');
            console.dir(result);
        } catch (err) {
            console.log(err);
        }
    }
}

app.js应用程序.js

const Server = require('./server/Server');
const DAO = require('./server/DAO');
const express = require('express');

const server = new Server();
const dao = new DAO();

server.start();
dao.connect();

Now I want to request my database using dao.getDataLastHour() in app.js, but the function is executed before application is connected to database.现在我想在 app.js 中使用dao.getDataLastHour()请求我的数据库,但是在应用程序连接到数据库之前执行 function。 I have tried to fix this problem by using promise, like this:我试图通过使用 promise 来解决这个问题,如下所示:

const promise = dao.connect();
promise.then(dao.getDataLastHour());

But it doesn't seem to work.但这似乎不起作用。

Perhaps I don't use Promise correctly.也许我没有正确使用 Promise 。

To use a then in you function,it need to return any result and turn it in a promise, or not use await, might it will work!要在你的 function 中使用 then,它需要返回任何结果并将其转入 promise,或者不使用 await,它可能会工作!

    async connect() {

            console.log("Connecting database.....");
            sql.connect(this.sqlConfig).then(pool => {
              if (pool)
                console.log("Database connected");
            }).catch (err{ 
            console.log(err);
        });
    }

sorry for the bad identification!抱歉识别错误!

Your method: dao.connect() does not return a promise.您的方法:dao.connect() 不返回 promise。 So the first thing would be to change that method to return a promise which you can then listen to then decide whether to run a query or not.因此,第一件事是更改该方法以返回 promise 然后您可以收听然后决定是否运行查询。 :

...
connect() {
     return new Promise((resolve, reject) => {
        try {
            console.log("Connecting database.....");
            let pool = sql.connect(this.sqlConfig);
            if (pool)
                console.log("Database connected");
                resolve("Success");
        } catch (err) {
            console.log(err);
            reject(err);
        }
     });
}
...

And then call your connect method like this:然后像这样调用你的连接方法:

dao.connect().then(
    success => { ... }, // you can continue querying 
    error => { ... } // something went wrong
);

Also try to read a bit about how to use promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise也尝试在这里阅读一些关于如何使用承诺的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Differences between promise and async: What is the difference between JavaScript promises and async await? promise 和 async 的区别:JavaScript promises 和 async await 有什么区别?

You can try something like this:你可以尝试这样的事情:

connect() {
 return new Promise((resolve, reject) => {

        let pool = sql.connect(this.sqlConfig, function(err) {
            if(!err) {
                resolve();
            }
            else {
                reject();
            }
        });
 });
}
 dao.connect().then(<<call function here>>)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM