Javascript callback being fired before function is

2019-08-08 19:42发布

I have 2 javascript functions, the first being a function which loads ajax content (via another function), and a second which is a callback function. They look like:

function createReply(callBack){
    ajaxPage('test.html', 'next-reply');
    callBack();
}

function updateNext(){
    document.getElementById('next-reply').id  = "reply-item";
}

createReply(updateNext);

As you can see, I am calling the createReply() function and passing it the name of the callback function, in this case updateNext()

In the createReply() function, I am calling another function which loads content via ajax. When this function is complete, the callback is supposed to be executed. The callback changes the id of the div in which the ajax content is being loaded. This is where the problem is occuring

I am getting the error:

Uncaught TypeError: Cannot set property 'innerHTML' of null 

Which is saying that it cannot change the content of the element with the id "next-reply" because it doesn't exist, and the reason it doesn't exist is because the callback function changes the id if that element. The intention is to have the callback fire after the ajax content has been loaded (ie; after the ajaxPage() function has been executed)

Can anyone see what the problem is? Is there a better way of implementing a callback function in plain javascript?

PS: no jQuery

2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-08 19:53

Right now you callback is executed right after the ajaxPage function. By right after I mean you do not wait for ajaxPage to return success. It is fired right after the ajax call goes out. It is very likely that it is not completed before your callback is fired.

查看更多
▲ chillily
3楼-- · 2019-08-08 20:10

As pointed out in the comments, this is due to the fact that AJAX calls happen asynchronously. The thread that createReply runs in continues to run before a response is returned from the server.

You'll need to re-factor ajaxPage to accept a reference to callback, and call it when the response is ready. Something like:

function createReply(callBack){
    ajaxPage('test.html', 'next-reply', callBack);
}

Then, in ajaxPage:

function ajaxPage(url, id, callback){
   //Do AJAX stuff

   //When the response is returned:
   if(callback) callback();
}
查看更多
登录 后发表回答