首页 > 解决方案 > 续集得到承诺

问题描述

如果我理解正确,我应该能够以这样的方式获得承诺:

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/ 如何使用节点的续集更新记录?

任何建议为什么这不起作用?

标签: node.jsexpresssequelize.js

解决方案


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);
    });
}

推荐阅读