[英]make callback for asynchronous function
I can write a callback function that will halt execution of one script until another is finished. 我可以编写一个回调函数,该函数将停止执行一个脚本,直到完成另一个脚本为止。 I found it here . 我在这里找到的。
dosomething(4, function () {
console.log("finished loop");
});
function dosomething(delay, callback) {
for (var i = 0; i < 100; i++) {
$("body").append(i + "<br>");
}
alert("done");
if (typeof callback == "function") callback();
}
However, this will not work with functions that are asynchronous. 但是,这不适用于异步功能。 I think that's the reason. 我认为这就是原因。
doAjax(4, function () {
console.log("finished ajax");
});
function doAjax(delay, callback) {
$.ajax({
type: "post",
url: "/echo/html/",
data: {
html: "some content",
delay: 4
},
dataType: 'html',
success: function () {
console.log("ajax done");
}
});
if (typeof callback == "function") callback();
}
I know it is a bit silly to ask how to incorporate my own callback for an asynchronous request since jQuery has them built in and I just used one, but I was wondering how it could be achieved. 我知道问如何为异步请求合并我自己的回调有点愚蠢,因为jQuery内置了它们,而我只是使用了一个,但是我想知道如何实现。 Is it as complex as writing an entire promise library? 它与编写整个Promise库一样复杂吗?
You aren't calling your callback after the request is done. 请求完成后,您不会再调用回调。
...
//HERE!
success: function(data){
if (typeof callback == "function") callback(null, data);
},
error: callback
...
//NOT BELOW
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.