【问题标题】:How do i return the result of a query from a function如何从函数返回查询结果
【发布时间】:2018-08-08 00:15:36
【问题描述】:

我不了解有关承诺的概念。有人可以给我一个示例如何使以下代码正常工作吗?请。

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

【问题讨论】:

标签: node.js asynchronous


【解决方案1】:

如果你知道任何关于 Promise 或 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);
       });
    })
}

然后,使用 await 得到结果:

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

OOOOOR,要容易:

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 
    }
});

【讨论】:

    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2017-04-13
    相关资源
    最近更新 更多