假设我有一个可以运行普通函数或 jquery AJAX 请求的页面加载器。我只想在 AJAX 请求成功(即完成
)时进入下一步,如果不成功(即失败
)则显示错误。
function runStep(stepText, functionToCall){
this.setStepText(stepText);
// call function
let result = functionToCall();
// if the function is jquery, wait for the result
if(result && typeof result.then === 'function'){
let self = this;
result.done(function(){
self.goToNextStep();
}).fail(function(){
self.showFailureMsg();
});
}
// if its a plain old function go to the next step
else {
this.goToNextStep();
}
}
我不明白的是;在我调用 done
或 fail
时,我已经运行了 jQuery AJAX 请求。那么附加这些处理程序还为时不晚吗?
最佳答案
Promises 的好处在于,您何时附加都无关紧要。一旦完成,状态就保持不变。
通过这种方式,您可以在应用程序的整个生命周期中传递已解决或已拒绝的 Promise,并且仍然会调用迟到的监听器。
const pg = Promise.resolve("foo");
const pb = Promise.reject("bar");
pg.then(v => console.log(v));
pb.catch(err => console.error(err));
由于 jqXHR 对象(即 $.ajax()
returns )实现了与 Promise 相同的接口(interface),您也可以随时附加。
const d = $.Deferred();
const dpr = d.promise();
d.resolve("foo");
dpr.then(v => console.log(v));
setTimeout(() => {
console.log("Even 3 seconds later it's still foo");
dpr.then(v => console.log(v));
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
考虑这个使用真实 XHR 的具体示例:
const post = $.ajax("https://jsonplaceholder.typicode.com/posts/1");
post.then(p => {
// We are in the callback of the request
// so we know that it is complete
console.log(p.title);
// Let's add another callback when we *think*
// it should be too late
post.then(latep => {
// Still possible
console.log(p.title)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 确定函数是否是 jQuery promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51937924/