1
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?

PPShein
  • 13,309
  • 42
  • 142
  • 227
  • possible duplicate of [What is the explicit promise construction antipattern and how do I avoid it?](http://stackoverflow.com/q/23803743/1048572) – Bergi May 10 '16 at 07:35

1 Answers1

2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @ppshein - On what line of code does that error occur? Are you passing `data` as an argument when you call the exported function? – jfriend00 May 10 '16 at 07:53
  • sorry, actual error is `mydata is not defined`. error showing `return mydata.updateAttributes(data);` that line. – PPShein May 10 '16 at 07:57
  • @ppshein - That's your code - I just copied from your question. You'd have to tell us what `mydata` is supposed to be. – jfriend00 May 10 '16 at 07:59
  • @ppshein - Do you perhaps mean it to be `data.updateAttributes(mydata)`? – jfriend00 May 10 '16 at 08:00