cswl
cswl

Reputation: 453

Promisifying an synchorous function

So, I have a code which is something like this.

     getSomethingAsync(something)
     .then(doSomethingAsync)
     .then(function(d) {
     _d = doSomethingSync(d);
     return doSomethingAsyncNext(_d);
     })
     .then(function(val) {
      //All done
      })
      .catch(err_handler);

I want to make it into something like.

     getSomethingAsync(something)
     .then(doSomethingAsync)
     .then(doSomethingSync)
     .then(doSomethingAsyncNext)
     .then(function(val) {
      //All done
      })
      .catch(err_handler);

Should I just change doSomethingSync which is:

      function(data) {
      // do a lot of things with data, throw errors for invalid data
      return changed_data;
      }

to:

      function(data) {
      // do a lot of things with data, throw errors for invalid data
      return new Promise(function(resolve,reject){
      resolve(changed_data);
      });
      }

or:

      function(data) {
      return new Promise(function(resolve,reject){
      // do a lot of things with data, reject for invalid data
      resolve(changed_data);
      });
      }

Upvotes: 0

Views: 144

Answers (1)

Felix Kling
Felix Kling

Reputation: 816940

Should I just change doSomethingSync which is ...

You don't have to change it all. If the return value of the callback is not a promise, it is directly used to resolve the promise returned by .then. The .then callback does not have to return a promise.

You could write

return Promise.resolve(changed_data);

but again, there is no need. return changed_data; will work just as well.

Upvotes: 5

Related Questions