一个有效的答案是:
function f() {
return new Promise(function(resolve, reject) {
resolve(4);
})
}
function g() {
return f().then((res) => {
return res;
})
.then((res) =>{
console.log(res);
})
}
g()
为什么?任何时候你从一个承诺中的then
声明中return
,它将它传递给下一个声明(然后或捕获)。尝试注释掉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
中,解析承诺会被延迟,因此不会阻止其他代码执行,但函数体可以使用从f
返回的值。
注意:要运行此操作,您需要节点7并且它应该使用--harmony-async-await
选项执行。
===========
编辑,包括新的代码片断
请看下面的代码。您必须使用它才能访问以前的对象 - 但是,在这种情况下访问它的位置取决于您。您可以在Promise.all
内部的每个承诺上致电,在这种情况下,或Promise.all
一次返回。请务必注意,Promise.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
*/
})
如果是返回4,你会链接'then's? –
@WiktorZychla?在'return f()。then((res)=> {return res;})'中,是否给出了'4'?由于'then'返回4? – user7361276
然后不返回4,它返回一个Promise。您作为参数传递的函数然后返回4. –