簡體   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