0

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');

7
  • Are you looking for either promise or async/await? Aside from asynchronous code, execution order is already guaranteed since Javascript is single-threaded. Commented Feb 22, 2020 at 9:33
  • @connexo: When I run my code. slowFunction2 is first executed and then slowfunction1 which is not sequential as far as I know. Commented Feb 22, 2020 at 9:40
  • Since you tagged this async/await, you seem to know the solution already. Use promises, and chain them instead of nesting callbacks. Commented Feb 22, 2020 at 9:41
  • @Bergi I know that async/await is a possible solution. But I don't know how to implement it. I would appreciate an answer with a possible solution. Commented Feb 22, 2020 at 9:42
  • 1
    Aside from asynchronous code You did read that part of the sentence? You explicitly tell slowFunction1 to wait a minimum of 10000 ms before executing fastFunction, where slowFunction2 is told to only wait a minimum of 1000 ms. Commented Feb 22, 2020 at 9:47

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

A promise-based function should not take a completion callback.
Great! That was what I was looking for! A simple and not unnecessary convoluted example! Thank you alot! I will try to adapt this solution to my problem.
@Bergi, true, and I have added the callback-less alternative to my answer now. I think it is still useful for the OP to see the transition from one pattern to the other, so they still recognise how it relates to their own attempt.
@trincot: How can I update the code if I don't know how long my slowFunction is running?
I think you mean something different. If it really runs during all that time then just wait for it to return. If however you mean it triggers an API action that is asynchrnoous then read the documentation of that API. Maybe there is a promise it returns or it calls a callback? It all depends. I suggest you ask a new question with a very concrete case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.