javascript - Promise in node is also nested
世界只因有你
世界只因有你 2017-06-05 11:11:11
0
5
773

1.

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. .

2. The solution code is as follows

//封装查询一条函数
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,,,

世界只因有你
世界只因有你

reply all(5)
洪涛

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,

我想大声告诉你
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?

PHPzhong
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?

迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template