node.js - 续集得到承诺
问题描述
如果我理解正确,我应该能够以这样的方式获得承诺:
var helper = null;
MyModel.findAll().then(result => { helper = result });
在示例中,这应该足够了,但我什么也没得到。如果我为整个调用分配一个变量,我会得到未决的承诺。我从示例中看到的唯一“区别”是我在 http 请求中调用它:
exports.somePostRequest = (req, res, next) => {
var helper = null;
myModel.findAll().then(result => { helper = result });
}
这完美地工作:
exports.anOtherrequest = (req, res, next) => {
myModel.findAll()
.then(result => {
res.status(200).json({message: result})})
}
我正在查看的一些示例: https ://sequelize.org/v3/docs/models-usage/ 如何使用节点的续集更新记录?
任何建议为什么这不起作用?
解决方案
var helper = null;
MyModel.findAll().then(result => { helper = result });
console.log(helper) // will be null
上述方法的问题在于,像第 2 行中的异步操作不会按照您期望的顺序发生。在 javascript 中发生的是第 1 行执行,第 2 行(异步操作)计划在所有同步操作执行后运行,第 3 行运行,最后所有异步操作将完成(本例中为第 2 行)。
所以简单来说,这里的执行顺序是:
line 1 completes >> line 2 is scheduled to complete later >> line 3 completes >> line 2 operation completes
您可以改为使用await
使其按顺序运行。就像是:
var helper = null;
helper = await MyModel.findAll();
console.log(helper); // not null; yayy
这样,一切都按顺序运行。但请记住,等待操作应该在async
函数内部。所以你的服务器应该看起来像:
exports.somePostRequest = async(req, res, next) => {
var helper = null;
helper = await myModel.findAll();
// or, var helper = await myModel.findAll();
// then do what you want with helper
}
替代解决方案使用.then
exports.somePostRequest = (req, res, next) => {
myModel.findAll().then(result =>
{
// work with the result here !
// console.log(result);
});
}
推荐阅读
- zooming - Mapbox:如何从 Mapbox 获取缩放级别的比例?
- pycharm - 我可以删除用户目录中的旧 .PyCharm 文件夹吗
- python - pyautogui 不能写 @ 符号
- php - 获取数据时获取字符串而不是 Carbon 对象
- java - 具有扩展 Comparable 的泛型类型参数的 Cast 接口
- vba - VBA: Can I use user input to specify which tab to run a VLOOKUP on?
- android - Volley Get Request not executing at all
- graphql - Apollo Link 数据突变
- python - How to have input recognize other types of variables?
- java - 如何使用 Android 的 ParcelFileDescriptor 和 Documents Provider 返回字节数据