Waterline ORM 将查找的结果分配给一个变量
Waterline ORM assign the result of find to a variable
我想合并 2 个查询的结果,然后 return 将它们合并为一个,如下所示:
test: async (req, res) => {
const valOne = TableOne.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const valTwo = TableTwo.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}
我知道上面的代码不会 return 因为它是异步的。我怎样才能做到这一点?
您提供的信息不多:node 版本、sails 版本等
这里有几种方法:
1. 使用承诺
2.使用回调链
3. 使用 await/async
如果您使用 sails 1.0 和节点 >= 8,您最好的选择是使用 await/async,因此您的代码应该像这样工作:
test: async (req, res) => {
let valOne, valTwo;
try {
valOne = await TableOne.find({ id: id });
valTwo = await TableTwo.find({ id: id });
} catch (err) {
return res.serverError(err); //or res.badRequest(err);
}
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}
我想合并 2 个查询的结果,然后 return 将它们合并为一个,如下所示:
test: async (req, res) => {
const valOne = TableOne.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const valTwo = TableTwo.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}
我知道上面的代码不会 return 因为它是异步的。我怎样才能做到这一点?
您提供的信息不多:node 版本、sails 版本等
这里有几种方法: 1. 使用承诺 2.使用回调链 3. 使用 await/async
如果您使用 sails 1.0 和节点 >= 8,您最好的选择是使用 await/async,因此您的代码应该像这样工作:
test: async (req, res) => {
let valOne, valTwo;
try {
valOne = await TableOne.find({ id: id });
valTwo = await TableTwo.find({ id: id });
} catch (err) {
return res.serverError(err); //or res.badRequest(err);
}
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}