-2

I dont understand the concepts about promises. Can someone just give me an example how to get the following code working? Please.

exports.getCategory=function(id){
 db.query("SELECT * FROM category_general =?",id, function(err, category){
  if(err) return err;
   return category;
 });
}
Sihoon Kim
  • 1,481
  • 2
  • 13
  • 32
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Aug 07 '18 at 04:24

1 Answers1

1

if you knew any thing about promise,or async/await

exports.getCategory=function(id){
    return new Promise((resolve,reject)=>{
       db.query("SELECT * FROM category_general =?",id, function(err, category){
          if(err) reject(err);
          resolve(category);
       });
    })
}

then,use await to get the result:

async function getQuery(){
    //your code or something else
    try{
        let result = await getCategory(id);
        // you can now use result
    }catch(e){
        //solve error
    }
}

OOOOOR,to be easy :

exports.getCategory=function(id,callback){ //place a Func to solve the category
       db.query("SELECT * FROM category_general =?",id, callback));
    })
}
//then use like this:

//some code .....
getCategory(id,function(err,category){
    if(err) {
        //.....
    }else{
        //your code to do with category 
    }
});
mscststs
  • 36
  • 2