等待$ .each直到第一个队列未完成

时间:2016-12-12 10:08:13

标签: javascript promise jquery-deferred deferred

以下是我的代码。如果我们使用set timeout函数,我们得到了所有数据,但我们没有使用我们没有得到来自我的本地数据库的检查数据。我希望在我的代码中使用延迟和承诺。提前致谢。

 function onclickToCall() {

        this.$('.check-list > .check-list-box').each(function (i) {
            var j = i + 1;
            var answer_req = $(this).attr("data-isReq");
            var checklist_guid = $(this).attr("data-guid");
            var question_type = $(this).attr("data-type");
            var yes_no = $("input:radio[name='radio_" + j + "']:checked").val();
            var notes = $(this).find('#txtAreaNotes_' + j).val();
            var attachment_url = $(this).find(".txtCameraImage").attr("data-path");
            var appConfig = DriverConnectApp.State.get('config_settings');
            var item = {};
            item.checklist_guid = checklist_guid;
            item.yes_no = yes_no;
            item.attachment_url = attachment_url;
            item.notes = notes;

            if (question_type == 2) { // For Vehical visual inspection
                var dataPromise = that.getInspectionData(checklist_guid);
                dataPromise.done(function (response, vh_image) {
                    var inspectionItem = {};
                    inspectionItem.vh_url = vh_image;
                    inspectionItem.details = response;
                    item.vh_inspection = inspectionItem;
                    that.detailsArr.push(item);
                });
            } else {
                item.vh_inspection = {};
                that.detailsArr.push(item);
            }
        });
        // after finish and push all data we need to call function here
        test();
    }

    getInspectionData: function (checklist_guid) {
        var that = this;
        var deferred = $.Deferred();

        that.dbchecklist.getVehicleInspectionlist(checklist_guid, function (data, res) {
            var details = [];
            if (data.length) {
                var img = data[0].vh_image;
                var arr = JSON.parse(data[0].vh_details);
                for (var k = 0; k < arr.length; k++) {
                    var items = {};
                    items.number = arr[k].number;
                    items.notes = arr[k].notes;
                    items.attachment_url = arr[k].attachment_url;
                    details.push(items);
                }
                deferred.resolve(details, img);
            } else {
                deferred.resolve(details, img);
            }
        });
        return deferred.promise(); 
    }

0 个答案:

没有答案