2

I have an asynchronous function that calls a synchronous function inside it. The asynchronous might be called concurrently, will the synchronous function in it cause any problems?

Can synchronous functions work concurrently calculating something for both callers at the same time? Or when the function is called, it waits for the previous call to finish?

9
  • If sync function is inside async one, you will have 2 async functions. So they must work concurently. Commented Mar 25, 2018 at 19:31
  • node is single threaded Commented Mar 25, 2018 at 19:31
  • Asynchronous in javascript isn't the same as parallel. So no it want cause any problems, because it will always wait for the previous call to finish. developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop Commented Mar 25, 2018 at 19:31
  • When you say "asynchronous function", what exactly do you mean? Do you mean declared with the async keyword? Or do you just mean a function that contains an asynchronous operation? If you include a code example, we could answer you a lot more specifically. Commented Mar 25, 2018 at 19:37
  • @marko how can I make it so that two callers of a function use the same function in parallel without waiting for completion? Commented Mar 25, 2018 at 19:51

2 Answers 2

4

Javascript is single-threaded. An asynchronous function doesn't mean that it can't run synchronous code, it just means that it can defer execution when it comes across await, and returns a promise. If some code in an asynchronous function calls something synchronous, that synchronous will run to completion before the asynchronous function continues - just like in a normal function.

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

3 Comments

Well explained sir :)
How can I make both the async and the sync func inside it not wait for a previous call? I want the code inside my async function to be executed once it is called, even if the previous call was 0.002 seconds ago and it is still executing.
@Mr.Blockchain, you can't interrupt the current thread like that - you just have to call the function you want like normal, and it'll be executed once the stack gets to it.
0

The synchronous functions inside the asynchronous function should not be a problem if you want to run them concurrently, take as example:

setTimeout(() => console.log("First"),4000);
setTimeout(() => console.log("Second"),1000);

These two will execute in the specified order, but the functions inside will run when their containing function lets them do so, thus the output in console will be:

Second
First

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.