在我的用户架构中,我有一个名为favorites的属性,它存储来自另一个存储引号的数据库的对象ID数组。我想在favorites属性中执行for循环,循环遍历每个id,根据来自其他数据库的id查找引用,将整个引用存储到新数组,然后将所有引用对象添加到array,将包含该数组的变量显示到ejs视图。这是我尝试过的代码:
router.get('/profile', authenticationMiddleware(), (req, res, next) => {
// console.log("After AuthenticationMiddleware of /profile load: The user username is: ", req.user.id)
let quoteIdFavorites = req.user.favorites
console.log("Started off by storing the ids of your favorite quotes to a variable: ", quoteIdFavorites)
let listOfQuotes = []
let getUserFavorites = new Promise((resolve, reject) => {
for (let i = 0; i < quoteIdFavorites.length; i++) {
Quote.findById({ _id: quoteIdFavorites[i] }, (err, result) => {
if (err) {
console.log("Database Error: ", err.message)
} else {
listOfQuotes.push(result)
console.log("Quote added. Iteration " + [i] + ": ", result)
}
})
}
console.log("Post for loop, here are your listOfQuotes: ", listOfQuotes)
resolve()
}).then(() => {
console.log("Promised resolved, now page should begin loading.")
console.log("And finally, here is what the listOfQuotes variable has in it: ", listOfQuotes)
res.render('profile', { user: req.user.username, favorites: listOfQuotes })
})
})
由于for循环不是一个promise,我试图将它转换为一个,然后一旦整个循环结束,我解析了promise,然后在.then()方法中,使用listOfQuotes渲染/ profile页面包含所需结果的变量。但是,在将所有结果存储到数组之前,.then()方法中的代码仍然首先运行。以下是控制台中输出的顺序:
// Step 1:
Started off by storing the ids of your favorite quotes to a variable: ["59f8defdfc62ebaba24ad627","59f8ddf69ad7b6ab6be6629e"]
// Step 2:
Post for loop, here are your listOfQuotes: []
// Step 3:
Promised resolved, now page should begin loading.
// Step 4: empty?
And finally, here is what the listOfQuotes variable has in it: []
// Step 5: load page
GET /profile 200 48.937 ms - 1905
// Step 6: why are the quotes just now being added to the array? the page has already loaded!
Quote added. Iteration 0: { _id: 59f8defdfc62ebaba24ad627,
updatedAt: 2017-10-31T20:37:17.279Z,
createdAt: 2017-10-31T20:37:17.279Z,
quote: 'how bout now',
author: 'well',
__v: 0 }
Quote added. Iteration 1: { _id: 59f8ddf69ad7b6ab6be6629e,
updatedAt: 2017-10-31T20:32:54.290Z,
createdAt: 2017-10-31T20:32:54.290Z,
quote: 'still work please',
author: 'thanks',
__v: 0 }
// Step 7: load in styles
GET /stylesheets/profile.css 200 37.570 ms - 5014
GET /javascripts/main.js 200 11.248 ms - 5800
非常感谢任何帮助!