简体   繁体   English

如何使用 SQLite3 和 node.js 从异步 function 返回值?

[英]How return a value from an asynchronous function with SQLite3 and node.js?

I'm trying to make a small database using SQLite3 for my discord bot (on node.js), and I'd like to make a function that updates the database with provided values (this part works) or return a value of the database.我正在尝试使用 SQLite3 为我的 discord 机器人(在 node.js 上)制作一个小型数据库,我想制作一个 function 来使用提供的值更新数据库(这部分有效)或返回数据库的值.

My problème is here, the returned value is always undefined...我的问题就在这里,返回值总是未定义的...

I have understood that SQLite3 commands are asynchronous so all the functions become asynchronous, but how I can make sure that the returned value be no longer undefined?我知道 SQLite3 命令是异步的,所以所有函数都变成异步的,但是我如何确保返回值不再是未定义的?

Here is my code:这是我的代码:

const sqlite3 = require('sqlite3');
const dbname = 'dbStocks';

module.exports = function gestionBDD(update, nomArticle, quantitéArticle) {
 console.log('1 ' + quantitéArticle);

 let db = new sqlite3.Database(dbname, (err) => {
  if (err) throw err;
  console.log('Démarrage de ' + dbname);
 });

 db.serialize(() => {
  nomArticle = '"' + nomArticle + '"';

  if (update) {
   //Si update est true : maj des quantités via le tableau articles

   db.run(
    `UPDATE stocks
                SET Quantité = (` +
     quantitéArticle +
     `)
                WHERE Article = (` +
     nomArticle +
     `)`
   );
  } else if (!update) {
   db.each(
    `SELECT Quantité FROM stocks WHERE Article  = (` + nomArticle + `)`,
    (err, data) => {
     console.log('2 ' + data.Quantité);
     return data.Quantité;
    }
   );
  }

  console.log('4 ' + quantitéArticle);
  db.close((err) => {
   if (err) throw err;
   console.log('Arrêt de ' + dbname);
  });
 });
};

And I get this result:我得到了这个结果:

1 undefined
4 undefined
3 undefined
Démarrage de dbStocks
2 500
Arrêt de dbStocks

(the 3 undefined is a console.log() in my index.js where my function gestionBDD is call) 3 undefined是我的index.js中的console.log() ,我的 function gestionBDD被调用)

You can return a promise that can get resolved later for function return like this:您可以返回一个 promise,稍后可以像这样为 function 返回解析:

return new Promise((resolve, reject) => {
 db.run(`query statement here`, (err, row) => {
  if (err) reject(err);
  resolve(row);
 });
});

Writing this at the top of the function to make it async function. when calling the function use ether await or then to get a return result data.将此写在 function 的顶部以使其异步 function。在调用 function 时使用 ether awaitthen获取返回结果数据。

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

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