3

在我的一个文件中,我拨打电话如下:

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”,它并没有改变任何东西。

在返回之前如何确保该值存在?

4

3 回答 3

2

我不熟悉 Amplify,但它的 API

通过发出的请求amplify.request将始终异步解决

因此,您必须将回调传递给getDropdownJobs, 以在jobsString填充后执行,并且任何依赖于该值的代码都会进入其中。

或者,您可以使用 Amplify 的 pub/sub 系统来订阅一个事件何时jobsString填充并在getDropdownJobs.

于 2012-11-14T21:03:15.613 回答
1

抱歉,如果我误解了您的问题,但是每次您执行这样的异步请求时,您都需要等待答案。在我提出替代方案之前,我倾向于遵循一些快速提示:

  • 通常像你getJobsDropdown这样的方法不会返回任何东西,或者它们可能会返回承诺。查看jquery Promise或这篇文章,了解更多关于链接这些相同 Promise 的高级材料。
  • 您可以使用的最简单的事情是回调,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);
}

这个有帮助吗?但愿如此。

干杯。

于 2012-11-14T21:07:11.637 回答
0

如果您使用 jQuery 并且不介意将 amplify 与 jQuery 框架耦合,您可以使用此插件,允许您使用 jQuery 延迟对象:

放大请求延迟插件

这是一篇包含一些背景信息和插件使用概述的文章:

为 AmplifyJS 请求添加 jQuery 延迟支持

于 2012-11-21T15:42:57.783 回答