我正在尝试返回“ checkins_each”,但是每次显示它都会返回一个空白列表[]。我认为checkins.list()在新线程中运行或与在新线程中运行的checkins.get()相同-是否有适当的方法返回checkins_each-它应该有一些记录?

console.log(jsondoc)显示jsondoc确实是一个大型json数据结构

// return data
var checkins = nano.use(settings.COUCHDB_PREFIX+'checkins');
var checkins_each = [];
checkins.list(function(err, body) {
    if (!err) {
        console.log('hi proximity loop')
        body.rows.forEach(function(doc) {
            console.log(doc.id);
            checkins.get(doc.id, function(err,jsondoc) {
                console.log(JSON.stringify(jsondoc));
                if (jsondoc.profile_id != profile_id) {
                    console.log('appending checkin');
                    checkins_each.push(jsondoc);
                }

            });
        });
        res.send({status: 'proximity', checkins: checkins_each});
    } else {
        console.log("error", err);
        res.send({status: 'fail', error: err});

    }

最佳答案

您必须阅读有关异步调用的信息,并使用Promisesasync-lib或类似下面的内容

var checkins = nano.use(settings.COUCHDB_PREFIX+'checkins');
checkins.list(function(err, body) {
    if (err)
        return res.send({status: 'fail', error: err});

    var checkins_each = [];
    function getRow(i) {
        if (i == body.rows)
            return res.send({status: 'proximity', checkins: checkins_each});

        var doc = body.rows[i];
        checkins.get(doc.id, function(err, jsondoc) {
            if (err)
                return res.send({status: 'fail', error: err});

            if (jsondoc.profile_id != profile_id)
                checkins_each.push(jsondoc);

            getRow(i + 1);
        });
    };

    getRow(0);
}


如果checkins.get返回Promise,则代码如下所示

var checkins = nano.use(settings.COUCHDB_PREFIX+'checkins');
checkins.list(function(err, body) {
    if (err)
        return res.send({status: 'fail', error: err});

    var promises = body.rows.map((row) => checkins.get(row.id));
    Promise.All(promises)
        .then(function (results) {
            var checkins_each = [];
            results
                .filter((res) => res.profile_id != profile_id)
                .forEach((res) => checkins_each.push(res))

            res.send({status: 'proximity', checkins: checkins_each});
        })
        .catch(err) {
            return res.send({status: 'fail', error: err});
        }
})

08-18 02:00