Pergunta

I usually do most of whats needed in the actual .done() function of any async type calls. But in this case I want to return the string as I need it multiple places but this function returns undefined all the time. The variable is out of scope of the async call so should be available to return no?

 var stringIWantBack = function getTableEditorFieldArray(pageName, tableId) {
     var searchString = 'webpagename[name ="' + pageName + '"] > tableid[id ="' + tableId + '"] > editor';
     var fieldArray;
     $.when(datatableUtility.GetInitStringXml())
         .done(function (returnedXml) {
             fieldArray = $(returnedXml).find(searchString).text();
             return fieldArray;

         })
         .fail(function (jqXhr, textStatus, errorThrown) {
             // alert("Error downloading projection data: " + textStatus + " Error: " + errorThrown);
             toastr.warning('Error downloading datatable editor fields array: ' + textStatus + ' Error: ' + errorThrown);
         });
 }
Foi útil?

Solução

You cannot return anything from an AJAX (asynchronous) function. It runs in the background, and the callbacks are called at some point in the future when it's done. By that point your function already returned and is finished.

What you can do is this:

function getTableEditorFieldArray(pageName, tableId) {
     var searchString = 'webpagename[name ="' + pageName + '"] > tableid[id ="' + tableId + '"] > editor';

     return $.when(datatableUtility.GetInitStringXml()).then(function (returnedXml) {
         return $(returnedXml).find(searchString).text();
     }).fail(function (jqXhr, textStatus, errorThrown) {
         // alert("Error downloading projection data: " + textStatus + " Error: " + errorThrown);
         toastr.warning('Error downloading datatable editor fields array: ' + textStatus + ' Error: ' + errorThrown);
     });
 }

Using .then() here instead of .done() will allow you to manipulate the data. The return there, will be sent to any .done() methods that you attach later.

For example:

getTableEditorFieldArray('test', 123).done(function(stringIWantBack){
    // This will be the value returned from `.then()`
    console.log(stringIWantBack);
});

Outras dicas

The problem isn't one of scope. You are quite right that you can return fieldArray from your getTableEditorFieldArray() function.

var fieldArray;
$.when(/* ... */ );
return fieldArray;

At this point though, fieldArray's value is undefined. The $.when() code might as well not even be there, since it will wait for the next tick (outside of this call stack) to do any work.

You must accept a callback to return the value asynchronously. Note that you can return the promise returned by $.when(), and multiple bits of code can call .done() on it. Those callbacks set up with .done() will be called in the order in which they were defined.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top