jQuery延迟解决

时间:2016-06-29 22:24:46

标签: ajax jquery-deferred

我正在努力让jQuery延迟为我工作。

我正在尝试使用下面列出的模式将使用jQuery $.ajax语句进行.then调用的许多函数调用链接在一起,但是每个函数都返回(所以当时的链继续)在ajax调用解决之前。

// earlier code runs fine to here
})
.then(function (r) {
    getCurrentYearAbsenceRequestData(); // calls function which contains a $.ajax request
})
.then(function (r) {
    restructureCurrentYearAbsenceData();
});

// further processing of results

上面提到的函数遵循以下模式:

function getCurrentYearAbsenceRequestData() {
var dfd = $.Deferred();

    var today = moment();
    var startOfCurrentHolidayYear = moment($clnt.holidayYearStartDate, "DD MMMM").format("DD/MM/YYYY");
    var startDayOfCurrentHolidayYear = moment().dayOfYear(startOfCurrentHolidayYear)
    var currentDayOfYear = moment().dayOfYear();

    if (moment(today).isBefore(startOfCurrentHolidayYear)) { //checks if holiday year started last year
        startOfCurrentHolidayYear = moment(startOfCurrentHolidayYear).subtract(1, "years"); //if so subtract 1 year from start of currently holiday year date
    };

    console.log("Start of Holiday year is " + startOfCurrentHolidayYear);

    var getOrgDataQuery = $apiUrl + "/web/lists/getbytitle('AbsenceRequests')/Items?$select=Id,AssocBranch/Title,DateFrom,DateTo,EmployeeLookup/EmployeeName,EmployeeLookup/Id,AbsenceType/AbsenceTypeShort,ReviewOutcome,TotalDays,AbsenceNotes&$expand=AssocBranch/Title,EmployeeLookup/EmployeeName,AbsenceType/AbsenceTypeShort&$filter=DateFrom ge '" + startOfCurrentHolidayYear + "'";

        $.ajax(_cnxRest.getRequest(getOrgDataQuery)) //calls personal library function which formats the parameter - this works OK)
            .done(function (r) {
                console.log("Get Org data success" + r);
                var $absDataCurrentYearData = r.d.results;
                $absData.allCurrentYear = $absDataCurrentYearData;

             dfd.resolve();
            })
        .fail(function (err) {
            logError(err);
        });
    };

    return dfd.promise();

};

我希望在随后的.then函数进展之前解析$ .ajax调用,并很高兴收到一些关于我出错的明智建议。

1 个答案:

答案 0 :(得分:1)

异步函数必须返回一个promise,以便通知其调用者异步。否则,调用者的.then(...).then(...)链将继续不考虑异步,这是问题中描述的症状。

你只是错过了一些回报,虽然代码也可以稍微整理一下。

// earlier code runs fine to here
.then(function (r) {
    return getCurrentYearAbsenceRequestData();
//  ^^^^^^
})
.then(function (r) {
    return restructureCurrentYearAbsenceData();
//  ^^^^^^
})
.fail(function (err) {
    logError(err); // by logging here you will see reported errors arising from the entire chain.
});

function getCurrentYearAbsenceRequestData() {
    var startOfCurrentHolidayYear = moment($clnt.holidayYearStartDate, "DD MMMM").format("DD/MM/YYYY");
    if(moment(moment()).isBefore(startOfCurrentHolidayYear)) {
        startOfCurrentHolidayYear = moment(startOfCurrentHolidayYear).subtract(1, "years");
    };
    var getOrgDataQuery = $apiUrl + "/web/lists/getbytitle('AbsenceRequests')/Items?$select=Id,AssocBranch/Title,DateFrom,DateTo,EmployeeLookup/EmployeeName,EmployeeLookup/Id,AbsenceType/AbsenceTypeShort,ReviewOutcome,TotalDays,AbsenceNotes&$expand=AssocBranch/Title,EmployeeLookup/EmployeeName,AbsenceType/AbsenceTypeShort&$filter=DateFrom ge '" + startOfCurrentHolidayYear + "'";
    return $.ajax(_cnxRest.getRequest(getOrgDataQuery))
//  ^^^^^^
    .then(function(r) {
        $absData.allCurrentYear = r.d.results;
        retrun r; // make the result available to the next step in the caller's .then chain, even if it's not going to be used
//      ^^^^^^
    });
};

主链可以简化为:

.then(getCurrentYearAbsenceRequestData) // calls function which contains a $.ajax request
.then(restructureCurrentYearAbsenceData)
.fail(function(err) {
    logError(err);
});

这里,retruns是在命名函数中写的那些。