gpt4 book ai didi

node.js - 等待 axios API 调用在 Node/Express 中完成

转载 作者:行者123 更新时间:2023-12-05 03:46:22 26 4
gpt4 key购买 nike

我确信这段代码很乱,因为我从来没有使用过这样的 API 调用。我面临的问题是,在生产环境中, Node 在呈现页面之前不等待 axios 调用完成。

我在开发环境中运行它没有任何问题。

router.get('/:id', middleware.isLoggedIn, (req, res) => {
var perPage = 9
var page = req.params.page || 1
User.findById(req.params.id)
.populate({
path : 'log',
options : {
sort : { date : -1 },
limit: 8,
skip: (perPage * page) - perPage
},
}).exec((err, foundUser) => {
if(err){
req.flash('error', 'Something went wrong. User not found.');
res.redirect('back');
} else {
Logbook.find({author: req.user.id}).countDocuments().exec((err, count) => {
if (err) return next(err)
axios.get('http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=' + foundUser.username + '&format=json')
.then(async response => {
var json = response.data;
if (json == undefined || json.Licenses == undefined || json.Licenses.License == undefined) {
if (err) {
console.log(err);
}
console.log('error1');
res.redirect('/profile/' + foundUser.id);
} else {
var data = json.Licenses;
var data2 = data.License;
var lic = [];
for (var i = 0; i < data2.length; i++) {
var lic = data2[i];
}
res.render('profile/index', {
user: foundUser,
json: lic,
current: page,
pages: Math.ceil(count / perPage),
logCount: count,
});
};
})
.catch(error => {
console.log(error);
res.redirect('/profile/' + foundUser.id);
});
});
}
});

真诚感谢任何帮助!

最佳答案

您的 async 关键字处于一个奇怪的位置,并且您没有使用 await 来指示 Node 应该等待该操作的结果。

一般来说,您将一个函数标记为async,并且在该异步 block 中,您可以等待异步操作的结果。

async function asyncFunc() {
try {
const response = await axios.get("/some_url_endpoint");
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}

您的示例可以这样重写:

async function searchLicenses(foundUser) {
const { username, id } = foundUser;
const url = `http://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=${username}&format=json`;

try {
const response = await axios.get(url); // node will wait for the response before continuing
const json = response.data;

if (json == undefined || json.Licenses == undefined || json.Licenses.License == undefined) {
if (err) {
console.log(err);
}
console.log('error1');
res.redirect(`/profile/${id}`);
} else {
const data = json.Licenses;
const data2 = data.License;
const lic = [];

for (var i = 0; i < data2.length; i++) {
var lic = data2[i];
}

res.render('profile/index', {
user: foundUser,
json: lic,
current: page,
pages: Math.ceil(count / perPage),
logCount: count,
});
};
} catch (error) {
console.log(error);
res.redirect(`/profile/${id}`);
}
}

router.get('/:id', middleware.isLoggedIn, (req, res) => {
var perPage = 9
var page = req.params.page || 1

User.findById(req.params.id)
.populate({
path: 'log',
options: {
sort: { date: -1 },
limit: 8,
skip: (perPage * page) - perPage
},
})
.exec((err, foundUser) => {
if (err) {
req.flash('error', 'Something went wrong. User not found.');
res.redirect('back');
} else {
Logbook.find({ author: req.user.id }).countDocuments().exec((err, count) => {
if (err) return next(err)
searchLicenses(foundUser.username)
});
}
});
}

关于node.js - 等待 axios API 调用在 Node/Express 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65329429/

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