加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

从$.ajax调用返回Javascript Promise

发布时间:2020-12-16 02:45:57 所属栏目:百科 来源:网络整理
导读:我试图将一个$.ajax()语句转换为es6 Promise并返回es6 promise.我的想法是,我将有一个创建,更新,删除对Microsoft Dynamics Web API的调用的应用程序层,它返回一个es6 Promise,以便我可以在多个页面上重用Create,Update,Delete调用.我已经阅读了有关es6 Promi
我试图将一个$.ajax()语句转换为es6 Promise并返回es6 promise.我的想法是,我将有一个创建,更新,删除对Microsoft Dynamics Web API的调用的应用程序层,它返回一个es6 Promise,以便我可以在多个页面上重用Create,Update,Delete调用.我已经阅读了有关es6 Promises的 Google,MDN和 David Walsh Blog文章以及几个SO问题,但我还没有完全详细说明.

在下面的代码中,当ExpenseUpload.js调用expenseTransactionSetAPI.Create(newExpenseTransactionSet).then(…));我看到执行到了then(),但是then()内部没有执行任何内容.我不太确定我需要做什么更改,以便我的代码执行实际上处理then(),我甚至不确定我是否正确使用es6 Promises.任何指导将不胜感激.

ExpenseUpload.js

"use strict";

requirejs.config({
    bundles: {
        'CCSEQ.WebAPI.js': ['Model/ExpenseTransaction','Model/ExpenseTransactionSet','API/ExpenseTransaction','API/ExpenseTransactionSet']
    }
});

require(["Model/ExpenseTransaction","Model/ExpenseTransactionSet","API/ExpenseTransaction","API/ExpenseTransactionSet"],function (ExpenseTransactionModel,ExpenseTransactionSetModel,ExpenseTransactionAPI,ExpenseTransactionSetAPI) {

let file;

$(document).ready(() => {
    setupHandlers();
});

function setupHandlers() {
    $("#csv-file").change((e) => {
        file =  e.target.files[0];
    });

    $("#btnUploadFile").click(() => loadFile());
}

function loadFile() {
    Papa.parse(file,{
        complete: (results) => {
            ImportExpenseTransaction(results.data);
            console.log("import complete");
        }
    });
}

function ImportExpenseTransaction(data) {
    let newExpenseTransactionSet = new ExpenseTransactionSetModel.ExpenseTransactionSet();
    newExpenseTransactionSet.SetName = $("#UploadName").val();
    newExpenseTransactionSet.Month = $("#UploadMonth").val();
    newExpenseTransactionSet.Year = $("#UploadYear").val();
    newExpenseTransactionSet.ImportDate = new Date();
    newExpenseTransactionSet.Status = 100000000;        

    let newExpenseTransactions = new Array();
    data.forEach((expense) => {
        if (expense[0] !== "PR EMP ID") {
            let newRecord = new ExpenseTransactionModel.ExpenseTransaction();
            newRecord. = expense[n];  
            ... // Load other records like above
            newExpenseTransactions.push(newRecord);
        }
    });

    let expenseTransactionSetAPI = new ExpenseTransactionSetAPI.ExpenseTransactionSet();
    let expenseTransactionAPI = new ExpenseTransactionAPI.ExpenseTransaction();
    expenseTransactionSetAPI.Create(newExpenseTransactionSet).
        then((data) => {
            console.log(data);
            console.log("Transaction Set Created");
            expenseTransactionAPI.
                Create(newExpenseTransactions[0]).
                then(() => {
                    console.log("Transaction Created");
                }).catch(() => {
                    console.log("failure");
                });
        }).catch(() => {
            (data) => {
                console.log(data);
                console.log("failure");
            }
        });        
}
});

CCSEQ.WebAPI.js

define("API/ExpenseTransaction",["require","exports","API/APIBase","Model/ExpenseTransaction"],function (require,exports,APIBase_1,Model) {
    "use strict";
    Object.defineProperty(exports,"__esModule",{ value: true });
    class ExpenseTransaction extends APIBase_1.APIBase {
        constructor() {
            super();
            this.ConvertToEntity = (data) => {
                let result = new Array();
                for (let i = 0; i < data.length; i++) {
                    let newRecord = new Model.ExpenseTransaction();
                    newRecord.[field] = data[i]["fieldName"];
                    .
                    .
                    .
                    result[i] = newRecord;
                }
                return result;
            };
        }
        Create(expense) {
            return new Promise((resolve,reject) => {
                $.ajax({
                    url: this.ExpenseTransaction,type: "POST",contentType: "application/json; charset=utf-8",dataType: "json",data: JSON.stringify(expense.toJSON()),success: (data) => { resolve(data); },error: (data) => { reject(data); }
                });
            });
        }
        ;
    }
    exports.ExpenseTransaction = ExpenseTransaction;
});
define("API/ExpenseTransactionSet","Model/ExpenseTransactionSet"],APIBase_2,{ value: true });
    class ExpenseTransactionSet extends APIBase_2.APIBase {
        constructor() {
            super();
            this.ConvertToEntity = (data) => {
                let result = new Array();
                for (let i = 0; i < data.length; i++) {
                    let newRecord = new Model.ExpenseTransactionSet();
                    newRecord.[field] = data[i]["fieldName"];
                    .
                    .
                    .
                    result[i] = newRecord;
                }
                return result;
            };
        }
        Create(expenseSet) {
            return new Promise((resolve,reject) => {
                $.ajax({
                    url: this.ExpenseTransactionSet,data: JSON.stringify(expenseSet.toJSON()),success: (data) => {
                        resolve(data);
                    },error: (data) => {
                        reject(data);
                    }
                });
            });
        }
        ;
    }
    exports.ExpenseTransactionSet = ExpenseTransactionSet;
});
//# sourceMappingURL=CCSEQ.WebAPI.js.map

解决方法

只需返回 ajax个请求,它就会返回一个类似承诺的对象.

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the
Promise interface,giving them all the properties,methods,and
behavior of a Promise

Create(expense) {
       return $.ajax({
            url: this.ExpenseTransactionSet,data: JSON.stringify(expenseSet.toJSON())
        });
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读