所以我有这段代码:

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块中返回新的诺言时正确捕获了错误?

最佳答案

长话短说,每个Promise链应该只包含一个捕获块。

您可以使用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);
        }
    );
});

关于javascript - 为什么这个 promise 不会转到下一个“那么”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49047907/

10-09 17:54
查看更多