承诺:链接方法并处理两个返回的对象?

Promises: chain methods and work with both returned objects?

我有这个代码:

return (entity.User.getProjects(req.user.id, ....))
    .then((list) => {
        // party with list object!
        return {
            list: list
        }
    }

我还想调用另一个方法,entity.Tag.getAllForUser,returns 一个 tags 列表。

(更新:我只需要使用承诺来做到这一点——我不能使用 async/await。)

此代码无效 - 它表示 listtag 均未定义:

return (entity.User.getProjects(req.user.id, ....))
    .then((list) => entity.Tag.getAllForUser(req.user.id))
    .then((list, tags) => {
        // party with both list and tags objects!
        return {
            list: list,
            tags: tags
        }
    }

我也试过将第二个调用链接到第一个:

return (
    entity.User.getProjects(req.user.id, ....).then((list) => 
    entity.Tag.getAllForUser(req.user.id))
 ).then((list, tags) => {
    // party with both list and tags objects!
    return {
        list: list,
        tags: tags
    }
}

但它又说 list 未定义。 有什么作用?

回答我自己的问题。请不要删除,因为这可能对其他人有用!

return (entity.User.getProjects(req.user.id, ....))
    .then((list) => Promise.all([list, entity.Tag.getAllForUser(req.user.id)]))
    .then(([list, tags]) => {
        // party with both list and tags objects!
        return {
            list: list,
            tags: tags
        }
}

只需简单地使用Async/Await

let list = await entity.User.getProjects(req.user.id, ....))
let tags = await entity.Tag.getAllForUser(req.user.id))

return {
        list: list,
        tags: tags
    }
}

如果您不能使用 Async/Await(尽管我建议使用它们),您可以使用 promise.all

Promise.all([
   entity.User.getProjects(req.user.id),
   entity.Tag.getAllForUser(req.user.id);
 ]).then(([list,tag])=>{
   // do here whatever you want
})

此处最好的解决方案是 Promise.all,它采用一个承诺列表,returns 一个已解析值的列表:

return Promise.all([
  entity.User.getProjects(req.user.id),
  entity.Tag.getAllForUser(req.user.id);
])
  .then(([ list, tags ]) => {
    // Party!
    return { list, tags };
  });

强制性建议使用 asyncawait

let [ list, tags ] = await Promise.all([
  entity.User.getProjects(req.user.id),
  entity.Tag.getAllForUser(req.user.id);
]);

return { list, tags };

这取决于您的请求是否独立

根据独立请求获取多个解析值:

假设我有 getUsers()getCities(),两者都是独立的(您不需要用户获取城市,反之亦然)。然后你可以使用 Promise.all:

Promise.all([getUsers(), getCities()])
.then(result => {
  // result here will be an array of two elements:
  // result[0] -> what getUsers resolves
  // result[1] -> what getCities resolves 
});

获取依赖请求的多个解析值:

如果你有,比方说,getUser(),其中 returns 一个用户,然后 getCouple(user),returns 一个与用户相关的人,然后getHouse(user1, user2),恰好两者都需要,可按如下操作:

const user = getUser();
const couple = user.then(u => getCouple(u)); // you can reuse a promise. This does not trigger then handler again, if
// the promise is settled will yield the settle value.
const house = user.then(u => {
  return couple.then(c => {
    return getHouse(u,c);
  });
});
使用 async/await 会更好:
async function() {
  const user = await getUser();
  const couple = await getCouple(user);
  const house = await getHouse(user, couple);
}