If there are two mongodb collections, one is users and the other is posts, and the corresponding users information is displayed in the posts list, the conventional asynchronous processing is too nested. Use Promise to solve it, and found that there is also a problem when solving promises. .
//封装查询一条函数
findOneData = function(db, colName, data) {
return new Promise(function(reslove, reject) {
db.collection(colName).find(data).toArray(function(err, data) {
if (err) {
console.log("数据查询错误" + err);
reject(err);
return;
}
reslove({ db: db, data: data });
});
});
};
db_conn()
.then(function(db) {
return findOneData(db, "test", {});
})
.then(function(data) {
console.log(data);
});
Is this method correct? It seems to have been solved, but I always feel like something is wrong,,,
PHP中文网2017-06-05 11:13:11
Promise is not the final solution and it is not necessarily much more elegant than callbacks, async/await is
滿天的星座2017-06-05 11:13:11
There are three points. Write the above code directly in the then of db_conn, and then return this.
Use catch in the outermost layer to capture exceptions.
Delete the console.log, it looks weird,
我想大声告诉你2017-06-05 11:13:11
db_conn()
.then(db=>{
return {
db:db,
test:'test',
data:{}
}
})
.then(findOneData)
.then(r=>{
console.log(r);
});
Finally, change the way your findOneData
receives parameters. Is it better?
PHPz2017-06-05 11:13:11
db_conn()
.then(db => findOneData(db, "test", {}))
.then(data => console.log(data));
Doesn’t this look more pleasing to the eye?
(async function() {
const db = await db_conn();
const data = await findOneData(db, "test", {});
console.log(data);
})();
Is this more pleasing to the eye?
迷茫2017-06-05 11:13:11
The Promise solution solves the problem of asynchronous callbacks without adding language elements, so there must be some limitations.
On top of the original callback, Promise will add at least one layer of callback, so when the original callback chain is very short, such as the subject of the question, there is only one layer, it seems that there is no advantage in using Promise, which is normal.
If you encounter more complex situations and more levels of nesting, you can see the value of using Promise.
Everyone upstairs has provided good writing methods, so I won’t say more.