0
我该如何检测函数中的AJAX调用是成功还是失败?假设我在其他地方称此功能。如何判断函数中的AJAX调用是否返回错误或成功?
file.js
function doSmallThing(param1, param2) {
$.ajax({
type: 'post',
url: 'some_url',
dataType: 'json',
...
success: function (result) {
// doStuff, signal that this code block is reached
},
error: function (error) {
// signal that this is reached
}
})
}
file2.js
import File from "..location/of/file.js";
class SomeComponent extends React.Component {
doSomething() {
// stuck here
if (File.doSmallThing(param1, param2) does not throw an error) {
doMoreThings();
} else {
// do nothing
}
}
}
如何将检测的结果:
File.doSmallThing(param1, param2)
请帮助。谢谢。
看看jquery Promise https://api.jquery.com/promise/ –
你可以将一个回调函数传入'doSmallThing',比如'doSmallThing(param1,param2,functionOnSuccess,functionOnFail)',然后调用'functionOnSuccess ()'当Ajax请求成功时失败。这将使控制流回到file2.js中。 –
您可以将doMoreThings设置为ajax函数的成功回调,而不是根据doSmallThing是否成功执行if包装doMoreThings – James