我试图返回"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});
}发布于 2018-08-19 18:47:05
您必须阅读有关异步调用的内容,并使用下面的Promises、async-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});
}
})发布于 2018-08-20 07:20:03
这是一个基于Aikon代码的尝试,由于某种原因,仍然返回empty一个空的checkins_each作为[]:
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});
})
});https://stackoverflow.com/questions/51911905
复制相似问题