search

Home  >  Q&A  >  body text

javascript - Promise in node is also nested

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

世界只因有你世界只因有你2760 days ago774

reply all(5)I'll reply

  • PHP中文网

    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

    reply
    0
  • 滿天的星座

    滿天的星座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,

    reply
    0
  • 我想大声告诉你

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

    reply
    0
  • PHPz

    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?

    reply
    0
  • 迷茫

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

    reply
    0
  • Cancelreply