LoopBack将查找结果保存到变量

时间:2018-09-06 13:30:22

标签: node.js loopbackjs

我正在尝试将查找结果保存到变量中,我环顾四周,找不到任何明确的答案,这是我想做的事情:

var data;    
myModel.findOne({
            where: {
                Key: 'myKey'
            }
        }, function(err, model) {
            if (err) {
                console.log(err);
            }
            data = model;
        });

我看着类似的question,但没有找到答案。

1 个答案:

答案 0 :(得分:1)

// Here you create a new variable called data
var data;

myModel.findOne({
  where: {
    Key: 'myKey'
  }
}, function(err, model) {
  // You create a new variable called data
  // it's different from the first data
  // The keyword var here means you want to declare a new variable
  // not use an existing one
  var data = model;
});

一个接近您的可行示例:

但是我认为您将很难知道何时使用data并遇到异步问题。

// Here you create a new variable called data
var data;

myModel.findOne({
  where: {
    Key: 'myKey'
  }
}, function(err, model) {
  // You create a new variable called data
  // it's different from the first data
  // The keyword var here means you want to declare a new variable
  // not use an existing one
  data = model;
});

这是我的建议之一:

function getMyData(callback) {
  myModel.findOne({
    where: {
      Key: 'myKey'
    }
  }, function(err, model) {
    callback(err, model);
  });
}

getMyData(function(err, data) {
  if (err)...

    // I can use my data here
    // ...
});

现在使用ES6,保证:

// findOne can be used with a callback, or it can return a Promise object
function getMyData() {
  return myModel.findOne({
      where: {
        Key: 'myKey'
      },
  });
}

getMyData()
  .then((data) => {
    // Use the data here ...
  })
  .catch((err) => {
    // Handle the error here ...
  });

编辑:使用Promise.all并行多个数据库请求运行

function getMyData(key) {
  return myModel.findOne({
    where: {
      Key: key,
    },
  });
}

Promise.all([
    getMyData('Key1'),
    getMyData('Key2'),
    getMyData('Key3'),
  ])
  .then((dataInArray) => {
    // Use the data here ...
    // dataInArray[0]
    // dataInArray[1]
    // dataInArray[2]
  })
  .catch((err) => {
    // Handle the error here ...
  });