【发布时间】:2020-07-12 12:34:06
【问题描述】:
我遇到了回调函数的问题,我找不到解决方案。我最近需要在回调中获取一个值以进行比较。问题是,当我比较时,我的变量仍然是初始值。
router.get('/qadashboard', (req, res) => {
var total = -1;
var options = {
method: 'GET',
uri: 'https://myurl.com/users',
json: true
};
request(options)
.then((response) => {
// Get Total
total = response.body.total;
})
.catch((err) => {
console.log('API Error - ', err);
});
if (total < 10) {
// Code here
} else {
// Code here
}
res.render("index");
});
Total 始终为 -1,我确信 response.body.total 不是 -1(始终返回正数)。如果我在回调函数中编写 console.log(response.body.total) 代码,它会返回正确的数字。 有什么方法可以等到回调执行完成,然后再比较是否总计
谢谢
【问题讨论】:
-
为什么不在请求回调中移动 if else 块?它向您显示默认值,因为在您之前执行其他代码时,promise 需要时间来解决。
-
then之后的所有代码,即 if 和 res.render 在请求解决之前触发,只需将其全部放入then..then进行重构requestlib 已弃用。 -
首先正确解释你的问题,然后在我的答案上加上-1
标签: javascript node.js express request-promise