为什么我的代码返回Promise {<pending>}

时间:2018-11-25 01:55:37

标签: mysql node.js

我是Node的新手,他们试图弄清楚我在这些承诺中做错了什么,我决定复制我的路线的完整代码以帮助您全面理解,并希望能有所帮助,谢谢!

router.get('/mygroups', function (req, res, next) {

    const db = require('../db.js');

    let grouplist = [];
    var groupcards = '';
    var imgreturned = '';

    var dbgroupreturn = new Promise(function (resolve, reject) {
        db.query('SELECT id, Group_name, Group_Activity, Group_Photo, Group_Creator, Group_members FROM groups ', function (error, results, fields) {
            if (error) throw error;

            const UserID = (req.user.user_id);

            for (var i = 0; i < results.length; i++) {
                var memberlist = results[i].Group_members;

                for (var j = 0; j < memberlist.length; j++) {
                    if (memberlist[j] == UserID) {
                        grouplist.push(results[i]);

                    }

                }
            }

            resolve(grouplist);
        })
    }).then(function (grouplist) {
        for (var k = 0; k < grouplist.length; k++) {
            var groupname = "<a href='group?" + grouplist[k].id + "'><div class='groupcarddiv'><h3>" + grouplist[k].Group_name + "</h3>";
            var groupActivity = "<p>" + grouplist[k].Group_Activity + "</p>";
            var groupPhoto = "<p>" + grouplist[k].Group_Photo + "</p>";
            var groupCreator = "<p>" + grouplist[k].Group_Creator + "</p>";

            var groupmemberlist = JSON.parse(grouplist[k].Group_members);

            async function findpicture(id) {
                return new Promise(function (resolve, reject) {
                    db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
                        if (error) {
                            throw error;
                        } else {
                            imgname = results[0].User_Profile_Photo;
                            resolve(imgname);
                        }
                    });
                });
                return imgreturned
            };

            for (var m = 0; m < groupmemberlist.length; m++) {
                var imgtag = await findpicture(groupmemberlist[m]);
                var imgtagresolved = imgtag.then(function (imgname) {

                    var imgreturned = '<img href="/uploads/' + imgname + ">";
                    return imgreturned;

                })
                console.log(imgtagresolved);
                // intention is to define groupMembers = as a div with the img tags inside, I am letting the console.log above to show results I am getting before be sure I can use the promise value into this var
            }



            var groupMembers = "<p>" + grouplist[k] + "</p></div></a>";
            groupcards += groupname + groupActivity + groupPhoto + groupCreator + groupMembers;
        }

        res.render('mygroups', {
            title: 'Groups',
            showgroups: groupcards,
        });
    })
})

我从第39行使用的console.log中获得了Promise {}回报,我试图理解Promise的概念,这花了我3天的时间和心情来理解如何将价值转化为变量被填充后,谢谢!

1 个答案:

答案 0 :(得分:0)

如果您谈论的是这一行代码:

console.log(imgtagresolved);

然后,这确实应由处于未决状态的承诺来实现。该变量来自此:

var imgtagresolved = imgtag.then(function (imgname) {...});

然后imgtag.then()会返回一个保证-始终。因此,您的代码完全按照预期的方式运行。 imgtagresolved是一个应有的承诺。 .then()方法就是这样。

您可以通过以下两种方式之一从承诺中获得价值:

  1. 在承诺中使用p.then(val => { /* access val in here */})
  2. let val = await p;标记的函数中使用诺言中的async

这就是从诺言中获取数据的方式。


您的代码似乎包含许多关于异步代码和诺言如何工作的问题和误解。这个地方并不是真正为您重写一整段代码的地方,如果我们愿意,我们甚至可以这样做,因为没有描述您真正要完成的工作。因此,目前尚不清楚我们如何能提供更具体的帮助。