2012-11-14 52 views
1

在我的文件之一,我拨打电话如下:如何确保放大请求在返回值之前完成?

var jobsString = getDropdownJobs(); 

它调用此函数:

function getDropdownJobs() { 

    var jobsString = amplify.store("JobsList"); 

    if (typeof jobsString === 'undefined') { 

     // Amplify sends a request for getJobs, if it exists in cache, it will return that value. 
     // If it does not exist in cache, it will make the AJAX request. 
     amplify.request("getJobs", function (data) { 

      // Leave a blank option for the default of no selection. 
      var jobsString = '<option value=""></option>'; 
      // Append each of the options to the jobsString. 
      $.each(data.jobs, function() { 
       jobsString += "<option " + "value=" + this.JobNo_ + ">" + this.JobNo_ + " : " + this.Description + this.Description2 + "</option>"; 
      }); 
      // Store the jobsString to be used later. 
      amplify.store("JobsList", jobsString); 

     }); 
    } 
    return jobsString; 

} 

"GetJobs" [增强的定义是:

amplify.request.define("getJobs", "ajax", { 
    url: "../api/Job/Jobs", 
    dataType: "json", 
    type: "GET", 
    cache: "persist" 
}); 

每当它返回,它是未定义的。我在AJAX定义中加入了“async:false”,它没有改变任何东西。

如何在返回之前确认该值是否存在?

+0

看看['$ .Deferred'(http://api.jquery.com/category/deferred-object/)。 – jbabey

回答

1

我不熟悉的放大,但its API说通过amplify.request取得

的要求永远是那么异步解决

,你必须回调传递到getDropdownJobs,以在jobsString被填充后执行,并且任何依赖于该值的代码都会在其中执行。

或者,您可以使用Amplify的发布/订阅系统订阅jobsString填写时的事件,并在getDropdownJobs期间向其发布。

0

对不起,如果我误解了你的问题,但每次你做这样的事情,一个异步请求,你需要等待答案。之前,我建议替代一些快速提示我倾向于遵循:

  • 通常的方法,如您getJobsDropdown不返回任何东西,或有可能,他们可以退货的承诺。看看jquery promises或这篇文章的更高级材料chaining那些相同的承诺。
  • 您可以使用的最琐碎的事情是回调,在getJobsDropdown的调用者上下文中的某个方法,您要在其中处理数据。这将允许你在简历你的程序数据准备就绪时。

试试这个:

function getDropdownJobs(callback) { 

    // some code (...) 

    amplify.request("getJobs", function (data) { 

     // your processing and when done 
     callback(); 

    }); 
} 

潜在的,你可以在回调传递数据。 getDropdownJobs的通常呼叫将是:

function processResults() { // This is your callback } 

function getData() { 

    // This is where you call getDropDownJobs 
    getDropDownJobs(processResults); 
} 

对您有帮助吗?但愿如此。

干杯。

相关问题