[英]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
i need to use shortLinks after Link.find({}) but array is empty. 我需要在Link.find({})之后使用shortLinks,但是数组为空。 Need to return shortLinks.
需要返回短链接。
Callbacks. 回调。 The
function(err, links)
is called asynchronously, so shortLinks
isn't populated until that function is called. 该
function(err, links)
是异步调用的,因此在调用该函数之前不会填充shortLinks
。 Your bottom console.log
is being called first, due to how callbacks work. 由于回调的工作方式,首先调用了您的底部
console.log
。
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks https://developer.mozilla.org/zh-CN/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks
need to use promise: 需要使用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.