worker11811 worker11811 - 2 months ago 6x
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() {

If I understand correctly
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
return p;

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


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"
    return j;
  return Promise.reject(j);

This will work:


But if you did it the other way around:


You would have to define your syncFunction as:

function syncFunction() {

  var j = "hi"
  return new Promise((resolve, reject) => {
      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) {
        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));