我们有一个需要运行API-1的需求。如果它成功并且API响应的结果是'true',我需要运行API-2,如果它成功并且API响应的结果是'true',我需要运行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,
});
}我在html中为jquery使用'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js‘。
首先,API调用'A‘在工作,控制首先命中’,然后‘块’和第二个API调用'B‘被执行。当控件命中第二个“然后”块时,数据、状态和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有谁能帮我解决以下问题吗?
,
发布于 2020-10-13 20:05:32
您可以使用async/await语法和for...of循环简化这一点,这将允许您一个接一个地执行请求,还可以将条件添加到循环之外的break中。
function fetchData(method) {
let url = `https://jsonplaceholder.typicode.com/todos/${method}`;
return $.ajax(url, {
type: 'GET'
});
}
async function runMethods() {
const methods = [1, 2, 'foo', 3, 4];
for (let method of methods) {
try {
const response = await fetchData(method);
// do your checking here
// break out of the loop if condition true
if (response.id == 3) {
console.log(response)
console.log('exiting on 3')
break;
} else {
console.log(response)
}
} catch (err) {
// you can also break on error here
console.log(`${err.status} for ${method} method`)
}
}
}
runMethods()<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
发布于 2020-10-13 19:43:03
基本上,您的函数runMethodGeneric返回一个承诺
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);
// HERE IS YOUR RETURN FUNCTION
return $.ajax(url, {
type: 'POST',
dataType: 'JSON',
data: jsonStr,
});
}因此,当您执行此函数时,需要有.then()来解析此函数的响应。
我想你可以在这里找到你的答案https://stackoverflow.com/a/16045729/11397634
https://stackoverflow.com/questions/64342019
复制相似问题