如何更新 mysql2 查询以不返回未定义的返回值?

发布于 2025-01-10 17:08:01 字数 1575 浏览 0 评论 0原文

我使用的是nodejs和mysql2。我将所有查询存储在一个类中。当我 console.log 结果时,我能够正确查看数据,但是当我使用 return 语句返回数据时,我得到了未定义的结果。我相信我需要使用承诺,但不确定如何正确执行。这是我当前返回未定义的内容,

    viewManagerChoices() {
        const sql = `SELECT CONCAT(first_name, ' ',  last_name) AS manager, id FROM employee WHERE manager_id IS NULL`;
        db.query(sql, (err, rows) => {
        if (err) throw err;
           const managers = rows.map(manager => ({ name: manager.manager, value: manager.id }));
           managers.push({ name: 'None', value: null });
           return managers;
        });
    };

这是我尝试使用以 Promise {} 返回的 Promise,

viewManagers() {
        return new Promise((resolve, reject) => {
            const sql = `SELECT CONCAT(first_name, ' ',  last_name) AS manager FROM employee WHERE manager_id IS NULL`;
            db.query(sql,
                (error, results) => {
                    if (error) {
                        console.log('error', error);
                        reject(error);
                    }
                    const managers = [];
           for (let i = 0; i < results.length; i++) {
               managers.push({ name: results[i].manager, value: i+1 });
           }
           managers.push({ name: "None", value: null });
                    resolve(managers);
                }
            
            )
        })
        
    }

我的类称为 Query,我通过执行以下操作来调用这些方法,

const query = new Query();
query.viewManagerChoices();
query.viewManagers();

I am using nodejs and mysql2. I am storing all my queries inside a class. When I console.log the results I am able to view the data correctly, however when I use a return statment to return the data, I am getting undefined. I believe I need to use promises, but am uncertain how to do so correctly. Here is what I have currently which is returning undefined,

    viewManagerChoices() {
        const sql = `SELECT CONCAT(first_name, ' ',  last_name) AS manager, id FROM employee WHERE manager_id IS NULL`;
        db.query(sql, (err, rows) => {
        if (err) throw err;
           const managers = rows.map(manager => ({ name: manager.manager, value: manager.id }));
           managers.push({ name: 'None', value: null });
           return managers;
        });
    };

This is my attempt at using promises which is returning as Promise {<pending>},

viewManagers() {
        return new Promise((resolve, reject) => {
            const sql = `SELECT CONCAT(first_name, ' ',  last_name) AS manager FROM employee WHERE manager_id IS NULL`;
            db.query(sql,
                (error, results) => {
                    if (error) {
                        console.log('error', error);
                        reject(error);
                    }
                    const managers = [];
           for (let i = 0; i < results.length; i++) {
               managers.push({ name: results[i].manager, value: i+1 });
           }
           managers.push({ name: "None", value: null });
                    resolve(managers);
                }
            
            )
        })
        
    }

My class is called Query and I am calling these methods by doing,

const query = new Query();
query.viewManagerChoices();
query.viewManagers();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你怎么这么可爱啊 2025-01-17 17:08:01

您对 viewManagers 的实现是正确的,但承诺不会使调用同步。

您需要使用 then 回调或在异步上下文中等待结果。

const query = new Query();
query.viewManagers().then((managers) => {
  // do stuff here
}).catch((error) => console.error(error.message));

或者

async someFunc() {
  const query = new Query();
  try{
    const managers = await query.viewManagers();
  }catch(error){
    console.error(error.message);
  }
}

一旦使用 Promise,您就不能在没有 async/awaitthen 标志的情况下获得返回值。一旦成为承诺,流程就会像原来一样继续。

例如:

// This is promise too because it has async flag.
// You cannot make it sync if you use promise in it
async myFunc(){ 
  const const query = new Query();
  const managers = await query.viewManagers();

  return managers;
}
// It actually returns Promise<...>

// Now if you want to use myFunc in another function 
// You need to do it the same way again
async anotherFunc(){ 
  const something = await myFunc();

  return something; // Returns promise
}

您可以在此处阅读有关 Promise 的更多信息

Your implementation for viewManagers is correct however promises don't make calls synchronous.

Either you need to use then callback or await the result in async context.

const query = new Query();
query.viewManagers().then((managers) => {
  // do stuff here
}).catch((error) => console.error(error.message));

or

async someFunc() {
  const query = new Query();
  try{
    const managers = await query.viewManagers();
  }catch(error){
    console.error(error.message);
  }
}

Once you use promise you cannot just get a returned value without async/await or then flag. Once it's a promise the flow continues as the original.

For example:

// This is promise too because it has async flag.
// You cannot make it sync if you use promise in it
async myFunc(){ 
  const const query = new Query();
  const managers = await query.viewManagers();

  return managers;
}
// It actually returns Promise<...>

// Now if you want to use myFunc in another function 
// You need to do it the same way again
async anotherFunc(){ 
  const something = await myFunc();

  return something; // Returns promise
}

You can read more about promises here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文