对数据执行操作时,有前途会陷入困境

I have a problem with promises. I have to do two queries to the database and I have to use then to read them. After that I have to merge them. What I did is as follows:

console.log("Start");
obj.find(query1).then(function(docs1) {
    console.log("HERE0");
    obj.find(query2).then(function(docs2) {
        // Merge reports
        console.log("HERE1");
        console.log("docs1");
        console.log("docs2");
        c = [...docs1.files, ...docs2.files];
        console.log("HERE2");
        for (let i = 0; i < c.length; i++) {
            for (let j = i + 1; j < c.length; j++) {
                console.log("i = " + i + " j = " + j);
                if(c[i].name == c[j].name) {
                    c[i].totals.invalid += c[j].totals.invalid ;
                    c[i].totals.valid += c[j].totals.valid ;
                    c[i].totals.total += c[j].totals.total;
                    c[i].totals.percentage = (c[i].totals.invalid / c[i].totals.valid) * 100;
                    c.splice(j, 1)
                }
            }
        }
        console.log("DONE");
        response.send(c);
    }, function (err) {
       logger.error(err.message);
       response.status(500).send(err.message);
    });
}, function (err) {
    logger.error(err.message);
    response.status(500).send(err.message);
});

输出:

Start
HERE0
HERE1
<valid docs1>
<valid docs2>

After he gets to the line c = [...docs1.files, ...docs2.files]; it's get stuck (doesn't get to the next prints) and I don't understand why. I can see those docs being printed to the console.log but why it does not work on that line?

Also, is there a better way of of performing the find call so there will be one nesting instead of two (one .then)?

EDIT: the find method uses Q.defer();. Maybe I need to use it two?

评论