嵌套承诺的问题

时间:2021-06-30 08:31:48

标签: javascript reactjs

我嵌套了 asyc await 函数调用,如下所示。我无法将第一个 promise 的返回值传递给下一个 promise。下面的代码有什么问题?

const ret = ProductRepository.getProductsBySameBrand(brand);
        ret.then(function (result) {
            shuffle(result.items).then(function (result) {
                console.log(result) //console is printing proper output
                return result; // This is not returning anything to the next chain
            });
        }).then(function (result) {
               // result is undefined
            context.setState({ products: result });
        });

1 个答案:

答案 0 :(得分:1)

也许我遗漏了一些东西,但你不能把 constext.setState 移到之前的承诺上吗?

const ret = ProductRepository.getProductsBySameBrand(brand);
        ret.then(function (result) {
            shuffle(result.items).then(function (result) {
                console.log(result) //console is printing proper output
                context.setState({ products: result }); // <-- move here
            });
        }); // <-- delete extra .then()