How to use YAHOO.util.Connect.asyncRequest and return the results?

I use YAHOO.util.Connect.asyncRequest to get data from a database, here is the code:

function getCountArticle(contentCurValue) { var handleSuccess = function (res) { var countPubmed = YAHOO.lang.JSON.parse(res.responseText); var contentCountPubmed = countPubmed.totalArticleRecords; alert(contentCountPubmed); //return 15 for example }; var handleFailure = function () { alert("Error connecting data : Bad pubmed query"); }; var callback = { success:handleSuccess, failure:handleFailure, timeout: 5000 }; var sURL = 'qct-list-article.html?term=' + contentCurValue + '&retstart=0' + '&retmax=1'; var request = YAHOO.util.Connect.asyncRequest('GET',sURL,callback); } 

I would like this function to return: "contentCurValue" (for example: 15), but when I try to use this code, I get "undefined":

 var test = getCountArticle(); alert(test); // return undefined, should return 15 

My error is probably related to an asynchronous request, but how can I get "var test = getCountArticle ()"; to wait for the results ?

+4
source share
1 answer

Since the call is inherently asynchronous, rather than trying to wait for an answer, it would be better for you to specify a callback function to execute on the data. You can change your method as follows:

  function getCountArticle(contentCurValue, callback) { var handleSuccess = function (res) { var countPubmed = YAHOO.lang.JSON.parse(res.responseText); var contentCountPubmed = countPubmed.totalArticleRecords; callback(contentCountPubmed); //return 15 for example }; // ... } 

then your call code:

  getCountArticle("contentCurValue", function(test) { alert(test); }); 

Any further execution using the value returned from your AJAX request will act inside your callback method.

This SO post is essentially the same problem, but not YUI: Getting undefined in javascript when ajax is called

+9
source

Source: https://habr.com/ru/post/1314451/


All Articles