1

Im using the following code which is working OK.

Now I need to return promise resolve but not sure how to do it in this case, there is nice way to do it? please ignore that the code is sync we are working on a tool which every external API method should return promise

This is the code

getExtendedFileContent: function(sHTML, aConfig) {
    var oDeferred = Q.defer();
    return aConfig ? this._process(sHTML, aConfig) : sHTML;
},

the this._process(sHTML, aConfig) & the sHTML should return

oDeferred.promise;

Cœur
  • 37,241
  • 25
  • 195
  • 267
NSS
  • 755
  • 1
  • 11
  • 30
  • What is `sHTML` a string? and what `this._process(sHTML, aConfig)` returns? – Satpal Apr 12 '16 at 13:25
  • `q.resolve(value)` to return a resolved promise. – Dmitri Pavlutin Apr 12 '16 at 13:25
  • Your `getExtendedFileContent` should only return the promise (`oDeferred.promise`). You should then resolve this promise with the values returned by either `sHTML` or `this._process(sHTML, aConfig)` – Phillip Apr 12 '16 at 13:26
  • @Satpal - sHTML is string and the process function return string either... – NSS Apr 12 '16 at 13:26

1 Answers1

2

Don't use Q.defer. Just use the Q function (or Promise.resolve if you're working with an ES6-compatible promise libary):

function getExtendedFileContent(sHTML, aConfig) {
    return Q(aConfig ? this._process(sHTML, aConfig) : sHTML);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks it will be great to explain why you against the q.defer since I saw many places where people use it... – NSS Apr 13 '16 at 11:34
  • @NinaS: To avoid the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572), mostly :-) It's just not necessary, adds complexity and introduces likelihood of errors. Also you should be using [`Q.Promise` instead of `Q.defer` anyway](http://stackoverflow.com/a/28692824/1048572) (when you really need it, which is rare enough given Q's great promisification helpers). See also [here](http://stackoverflow.com/q/35312418/1048572) – Bergi Apr 13 '16 at 11:38