简体   繁体   中英

Node js promise result use in other function

I am new in node js and i need result of my first query as a parameter in another function. Here my model:

return new Promise((resolve, reject) => {
var sql = "SELECT * FROM table";
        db.query(sql,
         (err, result) => {
           if (err) {
             return reject(err)
           }
           return resolve(result)
        });
   });

I need something like this

return new Promise((resolve, reject) => {
var sql = "SELECT * FROM table";
    db.query(sql)
    .then(rows.map(row =>{ 
            return arr[row.id] = this.getProduct(row.id);
    }))
})

Use Async/Await.

You can make a generic queryDb function which will call db and fetch result for any query.
mainFunction will wait for await to finish and fetch result which you can use in line below it.
Code also looks clean and easy to understand. Something like this,

async function mainFunction(){ 
  try{
    const query = `INSERT INTO aaa xxxxxx`;
    const result = await queryDb(query);
    //do whatever with the result;
    this.getProduct(result);

  }
  catch(e){
    //catch error
  }
}

function queryDb(sql){
  return new Promise( ( resolve, reject ) => {
    db.query(sql,
     (err, result) => {
       if (err) {
         return reject(err)
       }
       return resolve(result)
    });
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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