我有一个保存 Cat 信息的架构。然后我想创建一个包含所有 cat_url 的数组,但是当我在 dbs 调用之外调用该数组时,该数组为空
var cat_urls = [];
Cat.find(function (err, data) {
var stringify = JSON.stringify(data)
content = JSON.parse(stringify);
content.forEach(function (result) {
cat_urls.push(result.cat_url);
})
console.log(cat_urls, 'here')
})
console.log(cat_urls, 'here not working') // I want cat_urls to also be populated here
因此在 Cat.find() 调用 cat_urls 中具有如下值:
[ 'www.hello.co.uk', 'www.testing.co.uk' ] 'here'
但是在cat_urls = []
之外
我猜这与 Node js 不按特定顺序运行有关,但我该如何解决这个问题?
最佳答案
我认为它有效,但您的 find
函数返回一个异步解析的 promise 。
尝试:
var cat_urls = [];
Cat.find(function (err, data) {
var stringify = JSON.stringify(data)
content = JSON.parse(stringify);
content.forEach(function (result) {
cat_urls.push(result.cat_url);
})
console.log(cat_urls, 'here')
}).then(function(){
// Promise has completed, now this console log will trigger only after the cat's names are pushed.
console.log(cat_urls);
})
关于javascript - 为什么dbs调用后数组变量没有保存-node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39003524/