Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13837

How to use promise chaining in my coding in nodejs

exports.updateMyData = function (data) {
    var resultPromise = Q.defer();
    var errorResponse = function (err) {
        resultPromise.reject(err);
    };
    findById(data.id).then(function (mydata) {
        if (!mydata) {
            errorResponse("No item found to update");
        }
        mydata.updateAttributes(data).then(function (mydata) {
            resultPromise.resolve(mydata)
        }, errorResponse)
    }, errorResponse);
    return resultPromise.promise;
};

Above coding is working fine but I want to use promise chaining for above coding. Please help me how to use?

Upvotes: 1

Views: 54

Answers (1)

jfriend00
jfriend00

Reputation: 707926

You can just do this:

exports.updateMyData = function (data) {
    return findById(data.id).then(function (mydata) {
        if (!mydata) {
            throw new Error("No item found to update");
        }
        return mydata.updateAttributes(data);
    });
};

or chained like this:

exports.updateMyData = function (data) {
    return findById(data.id).then(function (mydata) {
        if (!mydata) {
            throw new Error("No item found to update");
        }
        return mydata;
    }).then(function(data) {
        return mydata.updateAttributes(data);
    });
};

Note how both these options return the internal promises rather than creating a new promise. Also, a throw within a .then() handler will reject that promise automatically.

Creating a new promise like your original code was doing when you can just return the one you already have is considered a promise anti-pattern and should be avoided.

Upvotes: 2

Related Questions