user3378165
user3378165

Reputation: 6896

Nested javascript promises

I have an AJAX call that based on its result - I send another call.

uploadDocument = function (doc1, doc2) {
    $.ajax({
        type: "POST",
        url: "/API/UploadDocs/addDocument",
        data: doc1,
        contentType: "application/json"
    }).then(function (result) {
        console.log(result);
        doc2.id=result;
        return $.ajax({
            type: "POST",
            url: "/API/UploadDocs/addDocument",
            data: doc2,
            contentType: "application/json"
        }).then(function (result) {
        });
    });
}

But I'm getting an Illegal invocation error, what am I doing wrong?

Upvotes: 0

Views: 40

Answers (2)

Marco Talento
Marco Talento

Reputation: 2395

You are doing promise chaining wrongly! When you return a promise you have to continue with the then that called the promise you are resolving.

Read the chaining section: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

uploadDocument = function (doc1, doc2) {
    $.ajax({
        type: "POST",
        url: "/API/UploadDocs/addDocument",
        data: doc1,
        contentType: "application/json"
    }).then(function (result) {
        console.log(result);
        doc2.id=result;
        return $.ajax({
            type: "POST",
            url: "/API/UploadDocs/addDocument",
            data: doc2,
            contentType: "application/json"
        });
    }).then(function (result) {
      //Continue here
    });
}

Upvotes: 1

rootkill
rootkill

Reputation: 629

Illegal Invocation error arises when there is some error in the data being passed through AJAX

Check the type of doc1 and doc2.. Also try passing processData:false to the ajax.

Upvotes: 1

Related Questions