gpt4 book ai didi

javascript - 使用 .then 函数时页面未加载

转载 作者:行者123 更新时间:2023-12-03 03:45:52 24 4
gpt4 key购买 nike

我一直在开发一个项目,它要求我在数据库中创建模式后使用 .then 函数,但由于某种原因,每次我尝试在中运行 res.render 函数时.then() 函数,页面不会加载。它告诉我我的应用程序正在端口上运行,并且我已连接到我的数据库,一切似乎都很好。我使用的是 cloud9,这是我的 index.js 文件代码

function getVenues (bars){
bars.map((eachBar) => {
Venue.findOne({
id: eachBar.id,
title: eachBar.name,
image: eachBar.image_url,
url: eachBar.url,
rating: eachBar.rating
}, (err, venue) => {
if(err) return (err);
if(!venue){
var newVenue = new Venue({
id: eachBar.id,
title: eachBar.name,
image: eachBar.image_url,
rating: eachBar.rating,
url: eachBar.url
}).save((err, venue) => {
if(err) return err;
})
}
})
})
}


router.get('/', function (req, res) {
res.header('Access-Control-Allow-Credentials', true);
request.get('http://ipinfo.io/' + req.headers['x-forwarded-for'], {json: true}, function (e, r){
client.search({
term: "bars",
latitude:r.body.loc.split(",")[0],
longitude: r.body.loc.split(",")[1]
}).then(response => {
getVenues(response.jsonBody.businesses).then(function(results){
res.render('home', {
bars: results,
term: 'Bars near you',
authenticated: req.isAuthenticated()
});
console.log(results);
});
console.log(req.isAuthenticated());
});
});
});

一切都已定义,并且在我的代码中没有显示任何错误。这里的问题是,如果我将 res.render 函数放在 .then 函数之外,它工作得很好并且一切都会加载,但现在,它只是继续加载并给出错误cloud9 站点中的错误 502 - 错误网关。有谁知道为什么会发生以及如何解决它?

最佳答案

问题是,您的函数 getVenues 不会返回定义 thencatchPromise >。要获取 field 数组作为结果,您需要合并每个 Venue.findOne 调用的结果。这可以通过在“内部”Promises 数组上使用 Promise.all 来完成:

return Promise.all(bars.map(bar => {
return Venue.findOne({...})
}))

这假设Venue.findOne返回值(或再次Promise)。如果 findOne 已经返回一个 Promise (应该像上面一样工作),但如果它只使用回调,则工作如下:

Venue.findOne({...}, (err, venue) => {
if (err) return (err)
if (venue) return venue
return new Promise((fulfil, reject) => {
let newVenue = new Venue({...})
.save((err, venue) => {
if (err) reject(err)
else fulfil(venue)
})
})

Promise 可能会返回错误。对于您使用的每个 Promise,您应该添加一个 catch。只需在每个 then 的右括号后添加一个 catch(或者最后一个 then if - 一般来说 - 你有一个级联的 then)您应该会看到发生了哪个错误:

client.search(...)
.then(...)
.catch(error => {
console.log(error)
})

关于javascript - 使用 .then 函数时页面未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45391442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com