-2

Given a function in a class that does processing on a text asynchronously. I also want my class to have a synchronous equivalent. Something like in the following example. Please help me how to achieve it.

class Processor {
  processAsync(text) {
    return new Promise((resolve, reject) => {
      anotherPromise(this.text).then(() => {
        resolve(processedText);
      }).catch((err) => {
        reject(new Error(`PROMISES FAILED`));
      });
    });
  }

// THIS IS THE FUNCTION I WANT TO WRITE WHICH RETURNS THE VALUE OF THE PROCESSED TEXT
  processSync(text) {
    return Promise.resolve(this.processAsync(text));
  }
}
function anotherPromise(text) {
  return new Promise((resolve, reject) => {
    if (someConditionWithText) {
      return resolve
    }
    return reject(someerror);
  });
}

Whenever I call processor.processSync('MyText') it returns a promise, than the expected value. What must I do? I read that Promise.resolve() should do the work, but it does not.

Klose
  • 323
  • 5
  • 17

1 Answers1

0

you can't transform an original asynchronous function into a synchronous function, or you can't use the original to make it synchronous. Everything happen in the the asynchronous function. So you have to copy the asynchronous function and modify inside. processAsync return a promise, so when you call it in processSync it return a promise too.

class Processor {
  processAsync(text) {
    return new Promise((resolve, reject) => {
      anotherPromise(this.text).then(() => {
        // anotherPomise has logic for validating text
        // and does something based on the text and resolve
        let processedText = processText(process.env.SomeEnvironmentVariable, this.text);
        resolve(processedText);
      }).catch((err) => {
        reject(new Error(`PROMISES FAILED`));
      });
    });
  }

// THIS IS THE FUNCTION I WANT TO WRITE WHICH RETURNS THE VALUE OF THE PROCESSED TEXT
  processSync(text) {
    return processText(process.env.SomeEnvironmentVariable, this.text)
  }
}
  • If I keep calling this frequently, it will not be great to store in the env variables :) I wonder why there is no solution to get a value from the promise? – Klose Jun 29 '18 at 16:15
  • @Klose Because this value doesn't exist yet. A promise is a *promise* of a value, literally. The meaning of 'asynchronous' is 'not synchronous', and this is not a coincidence. Whatever you're trying to do, you need to proceed from this fact. The question doesn't cover that 'not be great' thing and suggests that you have XY problem. Consider re-asking the question and addressing the real problem instead of expected solution (which is wrong). – Estus Flask Jun 29 '18 at 16:24