简体   繁体   English

如何将序列查询的结果推送到数组

[英]How to push the result of a sequelize query to an array

I have a node.js app and I'm using sequelize and mysql for the database. 我有一个node.js应用程序,并且我正在使用sequelize和mysql作为数据库。

I have been looking through the sequelize and bluebird docs trying to find a way to push a sequelize query to a an array. 我一直在浏览sequelize和bluebird文档,试图找到一种将sequelize查询推到数组的方法。 I have an array of orders that I loop through and then do a query on the address model. 我要遍历一系列订单,然后对地址模型进行查询。

I my query looks like this: 我我的查询看起来像这样:

    var objArr = [];
    models.address.findById(6).then(function(address){
      objArr.push(address);
    });
    console.log(objArr);

if I move the console.log inside the query it works, but outside objArr is empty. 如果我将console.log移入查询内部,则可以使用,但objArr外部为空。 I'm trying to figure out why that is. 我正试图找出原因。 Is it not possible to do this? 这是不可能的吗? I can't find the answer here or the docs I mentioned above. 我在这里或上面提到的文档中找不到答案。 I'm willing to read more docs, if somebody could point me in the right direction 如果有人可以指出正确的方向,我愿意阅读更多文档

Your code is asynchronous, that means that your console.log is executed before your push : 您的代码是异步的,这意味着您的console.log在执行push之前执行:

var objArr = [];
models.address.findById(6).then(function(address){
  objArr.push(address);
});
console.log(objArr);  // This code is executed before the objArr.push(address);

It's because the callback is asynchronous... the order looks like this: 这是因为回调是异步的...顺序看起来像这样:

var objArr = [];

models.address.findById(6);  //makes query, starts waiting for a response

// array is empty at this point
console.log(objArr);

//at a later time got answer, invoking callback
.then(function(address){

})

This is pseudocode, just to illustrate the point. 这是伪代码,只是为了说明这一点。 This code will not work 此代码不起作用

it's likely you're trying to do something like this: 您可能正在尝试执行以下操作:

function () {
  var objArr = [];
  models.address.findById(6).then(function(address){
    objArr.push(address);
  });
  console.log(objArr);
  return objArr
}

Instead you should handle all of this as asynchronous code. 相反,您应该将所有这些作为异步代码来处理。 Example with an callback: 带有回调的示例:

function (callback) {
  models.address.findById(6).then(function(address){
    callback(address);
  });
}

Or you should look up Promises. 或者,您应该查找Promises。 That's where that ".then" comes from 那就是“ .then”的来源

You can do something like: 您可以执行以下操作:

var objArr = [];
models.address.findById(6).then(function(address){
  objArr.push(address);
  return objArr;
})
.then(console.log);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM