0

i'm going deeper in javascript and recently i have decided to understand asynchronous in javascript. So i studied about ten hours and read about 20 articles about call stack, callbacks, promises, async/await, event loop and even V8 engine.

now, i know js is a single-threaded, synchronous and non-blocking language and use event loop, event table and message queue to handle async behaviour.

OK! great! but finally i don't understand that what things can be async?

every Authors use setTimeout, query to DB, AJAX and fs module as example for explaining about async. but we know they are all api and they are not a part of javascript core.

so, can we execute a for loop that calculate sum of 1 billion numbers asynchronously? if yes, HOW and if no, why? can i say async behaviour is just for web api or c++ api or etc?

5
  • Basically any function can be async -- async is just syntactic sugar for Promises. So any function that can return a Promise can be async. Commented Sep 21, 2019 at 2:04
  • @Herohtar thank you for your comment. can you answer this? : "so, can we execute a for loop that calculate sum of 1 billion numbers asynchronously? if yes, HOW?" Commented Sep 21, 2019 at 2:07
  • how? use setTimeout Commented Sep 21, 2019 at 2:10
  • @Herohtar - are you sure the question was about Promise/async/await? doesn't seem to be Commented Sep 21, 2019 at 2:11
  • @Herohtar i think i can't explain my question in right way! i want to know, can i execute any piece of code asynchronously or just there is a limit list of functions that they automatically execute asynchronously like setTimeout. Commented Sep 21, 2019 at 2:17

2 Answers 2

2

Please note, on my fairly high spec PC, this takes 4 seconds to do 1000 values! not very fast - you'd want to do say, chunks of 1,000,000 values - 100,000,000 values will take about 2 seconds ... 1,000,000,000 values is not possible, I get an out of memory error when trying to create such an array :p

You can do this a number of ways

Here's 2 different ways - neither is more performant that the other

Using setTimeout and a callback

function asyncSum(array, cb) {
    let result = 0;
    const fn = n => {
        result += array[n];
        if (n < array.length - 1) {
            setTimeout(fn, 0, n+1);
        } else {
            cb(result);
        }
    };
    fn(0);
}


asyncSum([1,2,3,4], console.log);

Using setTimeout and Promise

function asyncSumPromise(array) {
    return new Promise(resolve => {
        let result = 0;
        const fn = n => {
            result += array[n];
            if (n < array.length - 1) {
                setTimeout(fn, 0, n+1);
            } else {
                resolve(result);
            }
        }
        fn(0);
    });
}
asyncSumPromise([1,2,3,4]).then(console.log);

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

5 Comments

Thank you for this answer. i want to know, can i execute any piece of code asynchronously or just there is a limit list of functions that they automatically execute asynchronously like setTimeout. with your answer i guess that there is that limit list and we have to use setTimout for adding async behaviour to any piece of code.
You use Promise Abolfazl, or you use a a built-in async function, that doesnt block, like setTimeout
heres a good article medium.com/javascript-scene/…
1 billion values is definitely possible using generator functions ;)
@PatrickRoberts - I know, but I didn't want to over-complicate the code :p
-1

Any function can be async, the examples you listed are because async is commonly used when you are awaiting a response from a server, and you do not or can not block your program to wait for the response. You can use Promise, but you were talking about setTimeout to count to a billion. This is a recursive function. And here is a setTimeout to count to a billion. Enjoy the wait.

    let counter = 0;
function counting(){
    setTimeout(function(){
    if(counter < 1000000000){counter = counter + 1; counting();} }, 500);
}
counting();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

1 Comment

a bad copy and paste

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.