如何从包含 Promise 和 .then 的函数中 return 对象,以及如何在另一个函数中获取 returned 值?
How to return an object from a function that contains a Promise and a .then and how to get the returned value in another function?
我如何 return 来自包含 Promise 和 .then 的函数的对象;以及如何在另一个函数中从该函数获取 returned 值?这是包含 Promise 的函数,我想要 return 的对象是 obj:
function searchdb(user, key){
var ok;
const list = new Promise(function (resolve, reject) {
MongoClient.connect(uri, function(err, db) {
var dbc = db.db("chat");
dbc.collection("chat_messages").find({$or: [ {user1: key, user2: user}, {user1: user, user2: key} ]}).toArray(function (err, result){
if(err) {
reject(err);
} else {
resolve(result);
}
if(result[0].user1 == key){
ok = 1;
}
else{
ok = 2;
}
});
db.close();
});
});
var obj = {};
list.then(result => {
if (ok == 1){
obj[result[0].user1] = result[0].user2_seen;
}else{
obj[result[0].user2] =result[0].user1_seen;
}
console.log(obj); <--------------- here its working
}).catch(err => console.log(err.message));
return obj;
}
这是我想要获取 return:
的函数
function get(data){
suser = data[0]
obj = data[1];
for (var i in obj){
var key = Object.keys(obj[i])[0];
var a = searchdb(suser, key);
console.log(a); <-------------- here its not working
}
}
我无法 return 并从该函数获取 return,其他一切正常。请帮忙
在顶层的主函数中 return new promise
并在 obj promise 解决时解决它并将其存储在 newVarible
中。
然后使用 promise.all("newVarible")
之后,您将能够在任何地方解决承诺后获得 obj 的值。
我如何 return 来自包含 Promise 和 .then 的函数的对象;以及如何在另一个函数中从该函数获取 returned 值?这是包含 Promise 的函数,我想要 return 的对象是 obj:
function searchdb(user, key){
var ok;
const list = new Promise(function (resolve, reject) {
MongoClient.connect(uri, function(err, db) {
var dbc = db.db("chat");
dbc.collection("chat_messages").find({$or: [ {user1: key, user2: user}, {user1: user, user2: key} ]}).toArray(function (err, result){
if(err) {
reject(err);
} else {
resolve(result);
}
if(result[0].user1 == key){
ok = 1;
}
else{
ok = 2;
}
});
db.close();
});
});
var obj = {};
list.then(result => {
if (ok == 1){
obj[result[0].user1] = result[0].user2_seen;
}else{
obj[result[0].user2] =result[0].user1_seen;
}
console.log(obj); <--------------- here its working
}).catch(err => console.log(err.message));
return obj;
}
这是我想要获取 return:
的函数function get(data){
suser = data[0]
obj = data[1];
for (var i in obj){
var key = Object.keys(obj[i])[0];
var a = searchdb(suser, key);
console.log(a); <-------------- here its not working
}
}
我无法 return 并从该函数获取 return,其他一切正常。请帮忙
在顶层的主函数中 return new promise
并在 obj promise 解决时解决它并将其存储在 newVarible
中。
然后使用 promise.all("newVarible")
之后,您将能够在任何地方解决承诺后获得 obj 的值。