Modelesq
Modelesq

Reputation: 5402

.then() is not a function thrown when returning jQuery promises

I have my createUserData() function:

createUserData(user) {
    const dfd = new $.Deferred();
    $.ajax({
        url: './awesome/user',
        type: 'POST',
        dataType: 'json',
        data: user,
    })
    .then((response) => {
        dfd.resolve(response);
    })
    .fail((xhr) => {
        // do stuff with errors
        dfd.reject(errorMsg);
    });

    return dfd.promise;
}

And I want to be able to call it where ever...

createUserData(user).then((response) => {
    // do more stuff with that response
    // fire off other functions
    // But I can't get here...
});

I get createUserData(...).then() is not a function. Am I using promises wrong? I don't understand, I'm returning the promise in my function. What am I doing wrong?

Upvotes: 0

Views: 1424

Answers (2)

quirimmo
quirimmo

Reputation: 9988

You could directly return the $.ajax and concatenate that using the .done() and .fail().

Btw in your code the issue should be

return dfd.promise();

Upvotes: 0

AJ Funk
AJ Funk

Reputation: 3187

You need to invoke the promise method:

return dfd.promise();

Upvotes: 1

Related Questions