0

I am not an experienced Javascript programmer but I find it very difficult to execute 2 time-consuming functions in the row.

I have spent some days on studying promises or async/await but not success so far.

console.log("synch 1");
slowFunction1();
slowFunction2();
console.log("synch 2"); 

Most examples describe get json functions,setTimeOut etc. But in my case I have to do heavy mathematical calculations and the sequential execution is required. How could I do this?

9
  • 1
    Did you research of Promise? Commented May 21, 2019 at 11:54
  • you want run slowFunction1 and slowFunctuion2 simultaneously? Commented May 21, 2019 at 11:58
  • 2
    Note that even if you run slow functions asynchronously, they would most likely not be executed in different threads. So they won't run parallel - they'd still be executed sequentially but you might get a bit of "breathing room" between them. This could allow a UI to catch up and update between the calls, for example. Is that what you are after, or do you want to run them in parallel? Commented May 21, 2019 at 12:00
  • 1
    This article may be of help: Parallel programming in JavaScript using Web Workers Commented May 21, 2019 at 12:04
  • I always prefer a downvoting reason to the question/answer. It really helps people to grow in community with a confidence. Reason help to prevent mistakes in future Commented May 21, 2019 at 12:08

3 Answers 3

1

Depends on what you're trying to achieve and what the environment is. I will assume the slow function is blocking and you're going for the main thread not to be blocked during execution. Assuming you are talking about:

  1. Web:

Some example code would be:

var myWorker = new Worker('file-containing-slow-code.js');
myWorker.postMessage({execute: 'slowFunction1'});
myWorker.onmessage((msg) => {
  const {result, functionExecuted} = msg.data;
  console.log(result);
});
//contents of file-containing-slow-code.js
onmessage = function(e) {
  var result = funcs[e.data.execute]();
  postMessage({result, functionExecuted: e.data.execute});
}

const funcs = { 
  slowFunction1: () => {
    // do slow stuff;
  }
};
  1. Node.js
Sign up to request clarification or add additional context in comments.

1 Comment

I don't mind blocking, I want a specific function to be fully executed before moving on, but can't make it with await/async or promise.
1

You could wrap your functions in a promise like this, and only resolve when you want the code to continue:

function slowFunction1() {
  return new Promise(resolve => {
    setTimeout(() => resolve(), 1000)
  })
}

function slowFunction2() {
  return new Promise(resolve => {
    setTimeout(() => resolve(), 1000)
  })
}


console.log("synch 1");
slowFunction1().then(() => {
  slowFunction2().then(() => {
    console.log("synch 2");   
  });
})

This code should wait 1 second for each function before it console.log()'s "synch 2"

OR, you could use async/await instead of using .then(), like this:

function slowFunction1() {
  return new Promise(resolve => {
    setTimeout(() => resolve(), 1000)
  })
}

function slowFunction2() {
  return new Promise(resolve => {
    setTimeout(() => resolve(), 1000)
  })
}

async function main() {
  console.log("synch 1");
  await slowFunction1()
  await slowFunction2()
  console.log("synch 2");   
}

main()

7 Comments

I think I can understand better async/await but what puzzles me is where exactly I should insert all mathematical functions in slowFunction2() for example. Just above return new Promise?
I would have to know what your mathematical functions are first :p
The functions are like CalculateAverage(array[20000]); CalculatePearsonChiSquareTest(array[20000]); I have managed to run them sequentially with no problem and they are all running in a function doCalculations(array[2000]). Now I want to insert doCalculation() in your example above and I am confused with the syntax. This function has to finish up before moving to the next step.
I would recommend creating another question with the code for each function, and ask there. It is a bad idea to try and solve a problem that I have very little knowledge of in the comments section. If you would like, you can create a question and send me the link here and I'll have a look at it
What confuses me is the usage of setTimeout in the return: return new Promise(resolve => { setTimeout(() => resolve(), 1000) }). I understand that it is used to simulate a slow function. If I have a mySlowFunc() instead how would this be inserted in your example?
|
0

You got this right,you are trying to achieve a asychronous task.

Asynchronous Task

A task which will take some time to complete.

Way 1 - Callbacks

You need to give a callback to your further task. Let me give you an example.

function myHugeTask(callback) {
  // I need to do my task
 console.log('Hey I am  first task')
 callback() 
}

const someTaskWhichINeedToExecuteLater = () => {
 console.log('Hey I am after the first task')
}

myHugeTask(someTaskWhichINeedToExecuteLater)

Way 2 - Promises

Promises is like a real world promise. If I promised you then I will either complete it or reject it.

Let see

const myHugeTaskPromise = new Promise(resolve => {
  // Do my huge  task no matter how much time it takes
  console.log('I will complete first')
  resolve()
})

myHugeTaskPromise.then(()=>{
  console.log('Need to done when my promise get fulfilled')
})

2 Comments

I get: 'Need to done when my promise get fulfilled' 0 1 2 3 4 When I run : const myHugeTaskPromise = new Promise(resolve => { // Do my huge task no matter how much time it takes slowFunction(); resolve(); }) myHugeTaskPromise.then(()=>{ console.log('Need to done when my promise get fulfilled') }) function slowFunction() { for (let i = 0, p = Promise.resolve(); i < 5; i++) { p = p.then(_ => new Promise(resolve => setTimeout(function () { console.log(i); resolve(); }, Math.random() * 1000) )); } }
I am sorry, it does not work. I tried a functions that uses timeout and generates numbers in the // Do my huge task no matter how much time it takes and I take: Hey I am first task' 4:47:15.056 PM 'Hey I am after the first task' 0 1 2 3 4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.