所以我有这个代码:
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);
}
);
});
我预计即使Call 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);
}
);
});