Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

node.js - Async inside async function bug

I am trying to call simple view and within that I am making another query with the data from the view.

My problem is that I do not get it working ( this only gives me empty objects like this [{},{},{},{},{},{},{},{},{},{},{},{},{},{}]

any idea would be nice

My Code:

import { NextApiRequest, NextApiResponse } from 'next';
import { getConnection } from '../../../database/connection';
import { Song, Songs } from '../../../utils/song';

export default async function getPeople(req: NextApiRequest, res: NextApiResponse) {
    const connection = getConnection()
    connection.query("SELECT * FROM view3", (err: any, rows: Song[], _fields: any) => {
        if (err) {
            console.log(err)
            res.json({err: err})
            connection.destroy();
        } else {
            const response = rows.map( async(row:Song) => {
                const getIp = async() =>{
                    connection.query(`SELECT * FROM user WHERE ((ip = 12.12.142.91}) AND (item = ${row.id}))`,(err:any, rows:any, _fields:any) => {
                        if(err){
                            console.log(err)
                        }
                        else{
                            console.log(rows)
                            return rows;
                        }
                    })
                }
                

                return { voted: getIp(), id: row.id, vote: row.votes,}
            })
             res.status(200).json(response)
            connection.destroy();
        }
    })
} 
question from:https://stackoverflow.com/questions/66052357/async-inside-async-function-bug

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to await anything async, and since rows.map is given an async function, it's returning an array of promises, and you must use Promise.all

import { NextApiRequest, NextApiResponse } from 'next';
import { getConnection } from '../../../database/connection';
import { Song, Songs } from '../../../utils/song';

export default async function getPeople(req: NextApiRequest, res: NextApiResponse) {
  const connection = getConnection()
  try {
    // wrap the callback function in a promise
    const rows:any = await new Promise((resolve, reject) => connection.query("SELECT * FROM view3", async (err: any, rows: Song[], _fields: any) => {
      if (err) {
        return reject(err);     
      }
      resolve(rows);
    }));
    const getIp = async(id: string) =>{
      // convert the callback function to promise style syntax
      return new Promise((resolve, reject) => {
        connection.query(`SELECT * FROM user WHERE ((ip = 12.12.142.91) AND (item = ${id}))`,(err:any, rows:any, _fields:any) => {
          if(err){
            return reject(err);
          }
          return resolve(rows);
        })
      });
    }
    const response = await Promise.all(rows.map(async(row:Song) => {
        return { voted: await getIp(row.id), id: row.id, vote: row.votes };
    }));
    res.status(200).json(response)
    connection.destroy();
  } catch (err) {
    console.log(err)
    res.json({err: err})
    connection.destroy();
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...