实现node.js回调以获取结果 [英] Implementing node.js call back to get result

查看:88
本文介绍了实现node.js回调以获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node.js的完整入门者,所以如果我的问题很愚蠢,请原谅。实际上,我正在尝试从mongodb中获取一些结果并将其打印出来,但我无法获得所需的输出。

I'm a complete beginner in node.js so please excuse me if my question is foolish.Actually I'm trying to get some results from mongodb and print them but I'm unable to get desired output.

代码:

MongoClient.connect(url,function(err,db){
               if(err) throw err;

            var list=()=>{
                var arr=[]
                var blQ={blocked_user:data.tag_search_mail} 

                 db.collection("block_list").find(blQ,{"_id":0}).toArray((err,res)=>{

                         for(let i=0;i<res.length;i++){
                             arr.push(res[i]["blocker"])
                         }

                   });  
                 return arr  
            }
            var showList=(callback)=>{
               callback()
            }
            console.log(showList(list))//It's giving undefined
          // I wonder how can I print the returned array

建议后我尝试了什么:

var list = (callback) => {
                var arr=[]

                    var blQ={blocked_user:data.tag_search_mail} 

                      db.collection("block_list").find(blQ,{"_id":0}).toArray((err,res)=>{

                              for(let i=0;i<res.length;i++){
                                  arr.push(res[i]["blocker"])
                              }
                              callback(arr);    
                        });  

            }

            list((arr) => {
                console.log(arr);
            })


推荐答案

除了手动回调外,我建议您使用用于mongodb的node.js本机接口。

Rather than manual callbacks, I'd suggest you use the promise interface built into the node.js native interface for mongodb.

如果要将其放入函数中并返回结果进行通信并在完成后关闭数据库,则可以执行以下操作并从函数中返回promise

If you want to put this in a function and communicate back the result and close the DB when done, then you can do the following and return a promise from your function which the caller will use.

function getBlocked(data) {
    let openDb;

    close() {
        if (openDb) {
            openDb.close().catch(err => {
                console.log("Error closing db: ", err);
            })
        }
    }

    return MongoClient.connect(url).then(db => {
        openDb = db;
        const blQ = {blocked_user:data.tag_search_mail};
        return db.collection("block_list").find(blQ,{"_id":0}).toArray();
    }).then(results => {
        let blocked = results.map(item => item.blocker);
        close();
        return blocked;     // make this the resolved value of the promise
    }).catch(err => {
        close();
        throw err;          // rethrow to keep the promise rejected
    })
}

// usage
getBlocked(data).then(blocked => {
    // use blocked array here
}).catch(err => {
    // handle error here
});

这篇关于实现node.js回调以获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆