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,,,
Promise is not the final solution and it is not necessarily much more elegant than callbacks, async/await is
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,
Finally, change the way your
findOneData
receives parameters. Is it better?Doesn’t this look more pleasing to the eye?
Is this more pleasing to the eye?
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.