MachineLearner
MachineLearner

Reputation: 977

JavaScript Sequential function execution for multiple functions

I (first time JavaScript user since yesterday) managed to get JavaScript to run functions in sequential execution order (see code below) (credit to @CertainPerformance). I need to use the fastFunction in multiple slowFunctions. The current solution does not seem DRY (do not repeat yourself) to me and at the same time it does not guarantee the exectution order of slowFunction1 and then slowFunction2. What is the DRY solution to this problem in JavaScript? Can I force JavaScript to always run in sequential mode by some configuration? Using nested callbacks does not seem to be the most intelligent solution to me.

function fastFunction(message) {
  console.log(message);
}

function slowFunction1(callback, message) {
  setTimeout(() => {
    console.log('slowFunction1!');
    callback(message);
  }, 10000);
}

function slowFunction2(callback, message) {
  setTimeout(() => {
    console.log('slowFunction2!');
    callback(message);
  }, 1000);
}

slowFunction1(fastFunction, 'fast_Function');
slowFunction2(fastFunction, 'fast_Function');

Upvotes: 0

Views: 315

Answers (1)

trincot
trincot

Reputation: 350272

With async/await you can sequence asynchronous tasks as follows:

// Very handy utility function to get a promise that resolves after a given delay
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

function fastFunction(message) {
  console.log(message);
}

async function slowFunction1(callback, message) {
  console.log('slowFunction1!');
  await delay(2000); // two seconds
  callback(message);
}

async function slowFunction2(callback, message) {
  console.log('slowFunction2!');
  await delay(1000); // one second
  callback(message);
}

(async function() {
    // Put all your logic here, and await promises...
    await slowFunction1(fastFunction, 'fast_Function');
    await slowFunction2(fastFunction, 'fast_Function');
})(); // execute immediately

Now you will have the delays happening one after the other completes, so 2+1=3 seconds in (approximate) total execution time.

This mimics most what you had as pattern, but once you are using promises, you don't need the callback pattern anymore and can do it like this:

// Very handy utility function to get a promise that resolves after a given delay
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

function fastFunction(message) {
  console.log(message);
}

(async function() {
  console.log('slow part 1');
  await delay(2000); // two seconds
  fastFunction('fast_function');
  console.log('slow part 2');
  await delay(1000); // one second
  fastFunction('fast_function');
})(); // execute immediately

Upvotes: 1

Related Questions