LoopBack 将查找结果保存到变量

LoopBack Saving find result to a variable

我试图将查找结果保存到一个变量中,我环顾四周,找不到任何明确的答案,这就是我想要做的:

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

我看了这个类似的 question 但没有找到答案。

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