Javascript (NodeJS) 承诺未决?

use*_*276 3 javascript node.js

function  f () {
   return new Promise(function (resolve, reject) {

        resolve(4);
    })
}

function  g () {
    return f().then((res) => {return res;})

}

console.log(g());
Run Code Online (Sandbox Code Playgroud)

这返回 Promise { <pending> }

如果我返回res(当时)然后返回f(),为什么不是输出4

and*_*775 6

一个有效的答案是:

function f() {
    return new Promise(function(resolve, reject) {

        resolve(4);
    })
}

function g() {
    return f().then((res) => {
        return res;
    })
    .then((res) =>{
        console.log(res);
    })

}
g()
Run Code Online (Sandbox Code Playgroud)

为什么?任何时候你returnthen一个 promise的语句内部,它都会将它传递给下一个语句(then 或 catch)。尝试注释掉return res,你会看到它打印undefined.

==============
然而,在 ES7 中我们可以使用async/await. 我们可以使用以下代码复制上述内容:

function f() {
  return new Promise(function(resolve, reject) {
    resolve(4);
  });
}

async function g() {
  var a = await f();
  // do something with a ...
  console.log(a);
}

g();
Run Code Online (Sandbox Code Playgroud)

重要的是要注意console.log(g())仍然返回一个承诺。这是因为在实际的函数中g,promise 的解析会被延迟,因此不会阻止我们其余代码的执行,但函数体可以利用f.

注意:要运行它,您需要节点 7,它应该使用--harmony-async-await选项执行。

============
编辑以包含新的代码片段
查看以下代码。您必须使用 then 来访问先前的对象 - 但是,在这种情况下,您访问它的位置取决于您。您可以在 内的每个承诺上调用 then Promise.all,在这种情况下.then((userVictories) => ...).then(...)或一次Promise.all返回。需要注意的是 Promise.all 会在所有包含 resolve 的promise 后返回。

var membersArray = groupFound.members;
Promise.all(membersArray.map((member) => {
  return db.doneTodo.find({ 'victor._id': member._id }).then((userVictories) => {
    return {
      email: member.email,
      victories: userVictories.length,
    }
  }).then(obj => {
    /*
        obj is each object with the signature:
            {email: '', victories: ''}

            calling this then is optional if you want to process each object
            returned from '.then((userVictories) =>)'

            NOTE: this statement is processed then *this* promise resolves

            We can send an email to each user with an update
     */
  });
}))
  .then((arr) => {
    /*
        arr is an array of all previous promises in this case:
        [{email: '', victories: ''}, {email: '', victories: ''}, ...]

        NOTE: this statement is processed when all of the promises above resolve.

        We can use the array to get the sum of all victories or the 
        user with the most victories
     */
  })
Run Code Online (Sandbox Code Playgroud)