为什么这个承诺不会进入下一个 "then"?

Why does this promise not go to the next "then"?

所以我有这个代码:

Parse.Cloud.define("apiCall", function(request, response) {

    return Parse.Cloud.httpRequest({
        // API call 1
    }).catch(function(error) {
        /// Only perform this if the first call fails

        // Return valid json here, to mock the Parse.Cloud.httpRequest below
        return Parse.Promise.as({"data": "this is an expected JSON"});

        return Parse.Cloud.httpRequest({
            // API call 2
        });
    }).then(
        function(httpResponse) {
            /// This should perform after call 1, or call 2 if call 1 failed

            return Parse.Cloud.httpRequest({
                // API call 3
            });
        }
    ).catch(
        function(error) {
            console.log('FAIL');
            return response.error(error);
        }
    );
});

我希望即使调用 1 失败也能执行调用 3,但显然没有,它执行第一个 catch 块,然后执行最后一个 catch 块。当我在 catch 块中 return 一个新的承诺时,我以为我正确地发现了错误?

长话短说,每个 Promise 链应该只有一个 catch 块。

您可以使用 async/await 块重构您的代码,如下所示:

Parse.Cloud.define("apiCall", async function(request, response) {

    let response = null;
    try {
        response = await Parse.Cloud.httpRequest({
            // API call 1
        })
    } catch (error) {
        console.log({"data": "this is an expected JSON"});

        response = Parse.Cloud.httpRequest({
            // API call 2
        });
    }
    try {
        // Use response variable here
        let response2 = Parse.Cloud.httpRequest({
            // API call 3
        });
        return response2;
    } catch (error) {
        console.log('FAIL');
        return response.error(error);
    }
});

如果你想坚持使用 Promise 链,你也可以这样做:

Parse.Cloud.define("apiCall", function(request, response) {

    return new Promise((resolve, reject) => {
        Parse.Cloud.httpRequest({
            // API call 1
        })
        .then(function (data) {
            resolve(data);
        })
        .catch(function(error) {
            /// Only perform this if the first call fails

            // Return valid json here, to mock the Parse.Cloud.httpRequest below
            console.log({"data": "this is an expected JSON"});

            Parse.Cloud.httpRequest({
                // API call 2
            })
            .then(function (data) {
                resolve(data);
            })
            .catch(function (error) {
                reject(error);
            })
        })
    }).then(
        function(httpResponse) {
            /// This should perform after call 1, or call 2 if call 1 failed

            return Parse.Cloud.httpRequest({
                // API call 3
            });
        }
    ).catch(
        function(error) {
            console.log('FAIL');
            return response.error(error);
        }
    );
});