0
我想打包函数中的一些逻辑。逻辑应评估承诺的结果,然后返回一个值或抛出一个异常(根据承诺的值返回条件)。JS:条件返回函数包装承诺返回函数
让我分享一个simpliefied代码:
function GetID(exp, db){
let rxPtt = new RegExp(exp, 'gi');
let tID = db.collection('Col').find(
{ "Name": { $regex: rxPtt }}, {"_id": 1}).toArray();
let retVal = null;
tID.then(function (x){
if(x.length > 1){
console.log("More than one");
} else if (x.length < 1) {
console.log("Less than one");
} else {
retVal = x;
}
});
return retVal;
}
MongoClient.connect(url, function(err, db) {
if(err) throw err;
console.log(GetID('t', db));
db.close(function(){
console.log("Close connection");
})
});
这将返回:
# ./SmallScripts.js
null
Close connection
More than one
问题: 我感兴趣的是如何从一个承诺包装有条件返回值。如果我只是传承诺言并最终确定它,它就会起作用(见下文)。不过,我想把整个逻辑放到一个地方,然后返回ID。让我知道这应该做的正确的方式和任何提示如何可能的话考虑它。谢谢!
function X(db){
let r = db.collection('Col')
.find(
{ "Name": { $regex: /t/i}}, {"_id": 1}
).toArray();
return r;
}
MongoClient.connect(url, function(err, db) {
if(err) throw err;
let r = X(db);
r.then(function(res){
if(res.length > 1){
console.log("More than one");
} else if (res.length < 1) {
console.log("Less than one");
} else {
console.log(res);;
}
);
db.close(function(){
console.log("Close connection");
})
});
经过一些额外的研究,似乎没有任何意义,期望异步调用结果被打印在同步阶段(最外面的程序范围)。就像这里所说:https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –