繁体   English   中英

如何在collection.find({})中返回值

[英]How to return value in collection.find({})

var shortLinks = [];

Link.find({}, function (err, links) {

    if (err) {
        console.log(err);

    } else {

        links.map(link => {
            shortLinks.push(link.shortLink);
        });

    }
    console.log(shortLinks);//shortLinks has values, all okey
});

console.log(shortLinks); //shortLinks is empty

我需要在Link.find({})之后使用shortLinks,但是数组为空。 需要返回短链接。

回调。 function(err, links)是异步调用的,因此在调用该函数之前不会填充shortLinks 由于回调的工作方式,首先调用了您的底部console.log

https://developer.mozilla.org/zh-CN/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks

需要使用promise:

const shortLinks = [];

const getShortLinks = Link.find({}, function (err, links) {

    if (err) {
        console.log(err);

    } else {

        links.map(link => {
            shortLinks.push(link.shortLink);
        });

    }
});

getShortLinks.then(function(links){
    console.log(shortLinks);
}, function(err){
    console.log(err);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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