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?
答案 0 :(得分:2)
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.
答案 1 :(得分: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