0
我正在将数据填充到数组中。我向Postgress中的数据库发出了很多请求,并且我想将完成的数组响应给客户端。问题是,当通知数组完成时我无法到达,我怎么能知道过滤器何时完成了对db的所有选择调用?筛选数据后执行操作
result.filter(function(item){
//console.log(item.followed_by)
var query2 = 'SELECT user_id,action,date,element_refered FROM "notifications" WHERE user_id=' + "'"+ item.followed_by +"'"
dbp.sendDBRequest(query2,'blabla',function(results){
notifications.push(results)
console.log(notifications) //here has data
})
})
console.log(notifications) //here it doesnt have data
我有诺言尝试BT认为我没有错:
var p1 = new Promise(
function(resolve, reject) {
result.filter(function(item){
var query2 = 'SELECT user_id,action,date,element_refered FROM "notifications" WHERE user_id=' + "'"+ item.followed_by +"'"
dbp.sendDBRequest(query2,'blabla',function(results){
notifications.push(results)
})
})
resolve(notifications);
}
);
p1.then(
function(val) {
console.log(notifications)
})
.catch(
function(reason) {
console.log('Manejar promesa rechazada ('+reason+') aquí.');
});
编辑代码:
这与承诺的代码,但我得到了那么是不是一个过滤器(... )。然后不是函数
var notifications = []
var query = 'SELECT followed_by FROM "relations" WHERE follower=' +"'"+32+"'"
dbp.sendDBRequest(query,'blabla', function(result) {
result.filter(function(item) {
return new Promise(function(resolve, reject) {
var query2 = 'SELECT user_id,action,date,element_refered FROM "notifications" WHERE user_id=' + "'" + item.followed_by + "'"
dbp.sendDBRequest(query2, 'blabla', function(results) {
notifications.push(results);
resolve(notifications);
})
})
.then(function(val) {
console.log(notifications)
})
.catch(function(reason) {
console.log('Manejar promesa rechazada (' + reason + ') aquí.');
});
})
.then(function(response){
var secondResponse = response + '2';
return response;
})
.then(function(secondResponse) {
//facultad
})
.catch(function(err){
console.log(err)
})
})
好的谢谢你的回应,它返回TypeError:result.filter(...)。然后是不是我添加的代码完成的功能 – arnoldssss
啊!我的错。那么......渔获应该在诺言之后。看到更新的代码 –
我不知道你如何处理该sql函数中的错误,但为了落入catch块,你需要在主promise中的某处添加reject(error)。 –