续集得到承诺
Sequelize get promise
如果我理解正确的话,我应该能够像这样得到承诺:
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/
How to update a record using sequelize for node?
有什么建议为什么这不起作用吗?
var helper = null;
MyModel.findAll().then(result => { helper = result });
console.log(helper) // will be null
上述方法的问题在于,第 2 行中的异步操作不会按照您期望的顺序发生。 javascript 中发生的是第 1 行执行,第 2 行(异步操作)在所有同步操作执行后被安排到 运行,第 3 行 运行s,最后所有异步操作将完成(在本例中为第 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);
});
}
如果我理解正确的话,我应该能够像这样得到承诺:
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/ How to update a record using sequelize for node?
有什么建议为什么这不起作用吗?
var helper = null;
MyModel.findAll().then(result => { helper = result });
console.log(helper) // will be null
上述方法的问题在于,第 2 行中的异步操作不会按照您期望的顺序发生。 javascript 中发生的是第 1 行执行,第 2 行(异步操作)在所有同步操作执行后被安排到 运行,第 3 行 运行s,最后所有异步操作将完成(在本例中为第 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);
});
}