【发布时间】:2020-10-13 19:36:09
【问题描述】:
我们有一个需要运行 API-1 的要求。如果成功并且 API 响应的结果为“真”,我需要运行 API-2,如果成功并且 API 响应的结果为“真”,我需要运行 API-3。我尝试如下使用承诺链。
runMethodGeneric('A').then((data, status, xhr) => {
if(xhr.status === 200) {
if(data.result === 'true') {
runGenieMethodGeneric('B');
} else {
console.log('A result is false');
}
}
}).then((data, status, xhr) => {
console.log(data);
if(xhr.status == 200) {
if(data.result === 'true') {
runGenieMethodGeneric('C');
} else {
console.log('B result is false');
}
}
}).then((data, status, xhr) => {
console.log(data);
if(xhr.status === 200) {
if(data.result === 'true') {
console.log('C result is true');
} else {
console.log('C result is false');
}
}
}).catch((jqXhr, textStatus, errorMessage) => {
console.log(errorMessage);
});
runMethodGeneric 是运行所有 API 的通用方法,定义如下。
function runMethodGeneric(method) {
let url = 'http://192.168.1.253:55678/cl';
const json = {
user_data: data,
params: [],
gene_method: method,
requestedAction: 'RUN_GENIE_METHOD'
};
let jsonStr = JSON.stringify(json);
return $.ajax(url, {
type: 'POST',
dataType: 'JSON',
data: jsonStr,
});
}
我在 jquery 的 html 中使用“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”。
第一个 API 调用“A”正在运行,并且控制正在点击第一个“then”块,然后执行第二个 API 调用“B”。当控制点击第二个“then”块时,数据、状态和 xhr 都未定义,即使第二个 API 调用“B”正在工作并获得正确的结果。
jQuery.Deferred exception: Cannot read property 'status' of undefined TypeError: Cannot read property 'status' of undefined
at http://localhost:5000/chat.js:95:10
at j (https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:2:29999)
at k (https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:2:30313) undefined
谁能帮我解决以下问题。
- 我想知道这是否是做承诺链的正确方法?因为 runMethodGeneric 函数返回 promise。但不确定如何使用 API 调用 B 和 C 返回的那些承诺,因为我正在根据结果调用这些 API 调用。
- 如果上述方法不正确,如何做满足要求的promise链(运行API-1。如果成功并且API响应的结果为'true',则运行API-2,如果成功并且结果的 API 响应为“真”,运行 API-3)
- 我需要在“then”块中检查 xhr.status === 200 吗?我认为只有当 API 调用成功时,控制才会到达“then”块。这个假设正确吗?
【问题讨论】:
标签: javascript promise es6-promise