在javascript过滤器函数中使用promises并返回它

时间:2017-08-15 11:54:01

标签: asynchronous promise higher-order-functions

我正在尝试返回一个每个人会话的数组(我)没有跟随JavaScript的过滤器功能在promise的帮助下并将其作为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)
  })()
})

2 个答案:

答案 0 :(得分:1)

Array.prototype.filter是同步的 - 您无法使用异步过滤器过滤数组。

你可以做的是创建一个Promise数组,然后当所有这些都被解析后,返回响应:

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);
});

答案 1 :(得分:0)

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)

})