嵌套Promise链式调用时返回值无法传递到下一个链的问题排查
问题原因
你这段代码的核心问题是没有在第一层then的回调函数中返回内部的shuffle Promise实例。
Promise链式调用的规则是:每一个then都会返回一个新的Promise实例,这个新实例的结果由当前then回调的返回值决定:
- 如果回调返回普通值,这个值会直接作为下一个
then的入参 - 如果回调返回Promise实例,下一个
then会等待这个Promise执行完成,拿到它的resolve结果作为入参 - 如果回调没有写return语句,默认返回
undefined,下一个then拿到的入参就是undefined
你现有代码里第一层then的回调只执行了shuffle的调用逻辑,没有把这个异步操作的Promise return出去,自然后续链式调用拿不到内部shuffle的返回结果。
修复方案
方案1:修改原有链式写法,补上return
const ret = ProductRepository.getProductsBySameBrand(brand); ret.then(function (result) { // 此处新增return,把内部Promise抛到外层链式调用 return shuffle(result.items).then(function (shuffledResult) { console.log(shuffledResult) return shuffledResult; }); }).then(function (result) { context.setState({ products: result }); });
方案2:改用async/await写法,避免嵌套逻辑更清晰
async function updateShuffledProducts(brand) { const originProducts = await ProductRepository.getProductsBySameBrand(brand); const shuffledProducts = await shuffle(originProducts.items); console.log(shuffledProducts); context.setState({ products: shuffledProducts }); } updateShuffledProducts(brand);
内容的提问来源于stack exchange,提问作者Sona Shetty
相关产品推荐
相关产品推荐

