Asynchronous 在javascript过滤器函数中使用承诺并返回它

Asynchronous 在javascript过滤器函数中使用承诺并返回它,asynchronous,promise,higher-order-functions,Asynchronous,Promise,Higher Order Functions,我试图返回一个数组,其中包含会话(me)未遵循的everyone,并使用JavaScript的过滤函数借助承诺将其作为JSON响应发送 但它不起作用 提前谢谢 app.get('/explore', (req, res) => { P.coroutine(function *(){ let { id: session } = req.session, followings = yield db.query('SELECT id, username

我试图返回一个数组,其中包含会话(me)未遵循的everyone,并使用JavaScript的过滤函数借助承诺将其作为JSON响应发送

但它不起作用

提前谢谢

app.get('/explore', (req, res) => {
  P.coroutine(function *(){
    let
        { id: session } = req.session,
        followings = yield db.query('SELECT id, username, email FROM users WHERE id <> ? ORDER BY RAND() LIMIT 10', [session]),
        d = followings.filter(e => {
            db.is_following(session, e.id).then(s => s )   // returns boolean
        })

        res.json(d)
  })()
})
app.get('/explore',(req,res)=>{
P.coroutine(函数*(){
允许
{id:session}=req.session,
以下内容=yield db.query('SELECT id,username,email FROM users WHERE id?ORDER BY RAND()LIMIT 10',[session]),
d=以下内容。过滤器(e=>{
db.is_following(session,e.id)。然后(s=>s)//返回布尔值
})
res.json(d)
})()
})

Array.prototype.filter
是同步的-不能使用异步筛选器筛选数组

您可以做的是创建一系列承诺,然后在解决所有承诺后,返回响应:

var promises = [];
var d = [];
followings.forEach(function(e) {
  promises.push(
    db.is_following(session,e.id).then(function(s) {
      //following, push e onto `d`
      d.push(e);
    }).catch(function() {
      //not following, I assume, do nothing
    })
  );
});

Promise.all(promises).then(function() {
  //send the response after all the is_following requests have finished
  res.json(d);
});

Adam的解决方案工作得很好,但我找到了另一个使用async/await的解决方案

代码要少得多,而且是人类可读的

app.post('/explore', async function(req, res) {
  let
  { id: session } = req.session,
  exp = [],
  followings = await db.query(
   'SELECT id, username, email FROM users WHERE id <> ? ORDER BY RAND() LIMIT 10', 
   [session]
  )

  for (let f of followings) {
    let is = await db.is_following(session, f.id)
    !is ? exp.push(f) : null
  }

  res.json(exp)

})
app.post('/explore',异步函数(req,res){
允许
{id:session}=req.session,
exp=[],
followings=等待db.query(
'选择id、用户名、来自id所在用户的电子邮件?按兰德订购()限制10',
[会议]
)
对于(让f为以下内容之一){
let is=等待db.is_跟踪(会话,f.id)
!is?exp.push(f):空
}
res.json(exp)
})

我在这个项目中使用了这个逻辑。我发现了另一个使用async/await的解决方案