一个有效的答案是:
function f() {
return new Promise(function(resolve, reject) {
resolve(4);
})
}
function g() {
return f().then((res) => {
return res;
})
.then((res) =>{
console.log(res);
})
}
g()
为什么?任何时候你在一个 Promise 中的 then 语句中 return 时,它都会将它传递给下一个语句(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();
重要的是要注意console.log(g()) 仍然返回一个承诺。这是因为在实际的函数 g 中,解析 promise 会延迟,因此不会阻止我们的其余代码执行,但函数体可以利用来自 f 的返回值。
注意:要运行它,您需要节点 7,并且应该使用 --harmony-async-await 选项执行它。
============
编辑以包含新代码 sn-p
看下面的代码。您必须使用 then 来访问以前的对象 - 但是,在这种情况下,您在哪里访问它取决于您。您可以在 Promise.all 内的每个 promise 上调用 then,在本例中为 .then((userVictories) => ...).then(...) 或一旦 Promise.all 返回。需要注意的是,Promise.all 一旦 all 承诺它包含解析,就会返回。
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
*/
})