wtsang11 / TechExplore

MIT License
0 stars 0 forks source link

Introduction #188

Open wtsang11 opened 3 years ago

wtsang11 commented 3 years ago

http://localhost/TechNotes/wp-admin/post.php?post=1477&action=edit

VSC: http://localhost/lab/python/utilities/study_codes/opencodes.php?f=/Users/wtsang/Lab/javascript_programming/javascript_cookbook/

Other Studies

Javascript for web developers https://github.com/wtsang11/TechExplore/issues/127

Secrets of Javascript ninja https://github.com/wtsang11/TechExplore/issues/156

wtsang11 commented 3 years ago

See how transform an utility function that provides a computational service and return a Promise object to call back the Resolve function or Reject function i.e. Promisifiy a legacy function

// The original function
function factorializeNumber(number, successCallback, failureCallback) {
  if (number < 0) {
    failureCallback(
      new Error('Factorials are only defined for positive numbers'));
  }
  else if (number !== Math.trunc(number)) {
    failureCallback(new Error('Factorials are only defined for integers'));
  }
  else {
    setTimeout(() => {
      if (number === 0 || number === 1) {
        successCallback(1);
      }
      else {
        let result = number;
        let currentNumber = number;
        while (currentNumber > 1) {
          currentNumber -= 1;
          result *= currentNumber;
        }
        successCallback(result);
      }
    }, 5000);  // This hard-coded 5 second delay simulates a long async process
  }
}

// The wrapper that will return a Promise object
function factorializeNumberPromise(number) {
  return new Promise((resolve, reject) => {
    factorializeNumber(number,
      result => {
        resolve(result);
      },
      error => {
        reject(error);
      });
  });
}

// Using the wrapper
console.log('Creating the promise');
factorializeNumberPromise(6).then(result => {
  console.log(`6! = ${result}`);
});

// Test the reject function
console.log('Creating the promise');
factorializeNumberPromise(-6).then(result => {
  console.log(`-6! = ${result}`);
})
  .catch(error => {
    console.log(error);
  });
console.log('Now it\'s all over except the waiting...');