-1

I have a javascript function with two promises:

uploadDocument = function (formData, order) {
    $.ajax({
        type: "POST",
        url: "/API/Documents/addDocument",
        data: formData,
        contentType: false,
        processData: false
    }).then(function (documentID) {
        order.referenceID = documentID;
        return $.ajax({
            type: "POST",
            url: "/API/Documents/addOrder",
            data: ko.toJSON(transaction),
            contentType: "application/json"
        });
    }).then(function (result) {
        return 'success';
    });
}

That works perfectly, the API calls success.

the call to the function is:

uploadDocument(formData, order).then(function (data) {
     console.log('success');
})

At this point I'm getting an error:

Uncaught TypeError: Cannot read property 'then' of undefined

What am I doing worng?

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
user3378165
  • 6,546
  • 17
  • 62
  • 101
  • Possible duplicate of [TypeError: Cannot read property 'then' of undefined](https://stackoverflow.com/questions/24788171/typeerror-cannot-read-property-then-of-undefined) – alexmac Aug 31 '17 at 15:54
  • Debug your code. Set breakpoints and examine variables. Insert `console.log` statements. –  Aug 31 '17 at 15:54
  • It's essentially a typo, which could be found like any other bug with a bit of standard debugging technique and thinking about the error message. In that sense, no, it's not a "useful" question, which is the criterion for downvoting. –  Aug 31 '17 at 15:56

1 Answers1

2

You need to return your $.ajax() and then use then on it. Without return the function returns undefined by default, so why you get an error. See return before $.ajax(...).then(...).

uploadDocument = function (formData, order) {
    return $.ajax({
        type: "POST",
        url: "/API/Documents/addDocument",
        data: formData,
        contentType: false,
        processData: false
    }).then(function (documentID) {
        order.referenceID = documentID;
        return $.ajax({
            type: "POST",
            url: "/API/Documents/addOrder",
            data: ko.toJSON(transaction),
            contentType: "application/json"
        });
    }).then(function (result) {
        return 'success';
    });
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112