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

Using promises in a javascript filter function and returning it

我正在尝试 return 每个人的数组(我)在承诺的帮助下没有跟随 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)
  })()
})

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

您可以做的是创建一个 Promise 数组,然后当所有 Promise 都被解析时,return 响应:

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)

})