worker11811 worker11811 - 4 months ago 8
Javascript Question

Should synchronous code called by Promise .then create a new Promise

I've implemented some code, where asynchronous code is followed by some some synchronous functions. For example:

function processSomeAsyncData() {
asyncFuncCall()
.then(syncFunction)
.catch(error);
}


If I understand correctly
then
is also a Promise. Should I then in the synchronous code also create a promise?

function syncFunction() {
const p = new Promise (function (resolve, reject) {
//Do some sync stuff
...
resolve(data);
}
return p;
}


If that isn't necessary, how do you reject the promise from the synchronous code if an error occurred?

Answer

You don't need to create a new promise explicitly. There is an easier way.

This example is contrived because it will never fail, but the point is that you don't have to create a promise and you don't have to return a resolve(val).

function syncFunction() {
  var j = "hi"
  if(j){
    return j;
  }
  return Promise.reject(j);
}

This will work:

asyncFunction()
  .then(syncFunction);

But if you did it the other way around:

syncFunction()
  .then(asyncFunction);

You would have to define your syncFunction as:

function syncFunction() {

  var j = "hi"
  return new Promise((resolve, reject) => {
    if(j){
      return resolve(j);
    }
    return reject('error');
  })  
}

Edit: To prove to all you non believers out there, give this guy a shot locally on your computer. Proves that you have these many options available to you. :)

var Promise = require('bluebird');


function b(h) {
    if(h){
        return h;
    }
    return Promise.resolve('hello from b');
}

function a(z) {
    return new Promise((resolve, reject)=> {
        if(z){return resolve(z)};
        return resolve('hello from a');
    })
}

a().then(b).then(x => console.log(x)).catch(e => console.log(e));
b().then(a).then(x => console.log(x)).catch(e => console.log(e));