Abolfazl B
Abolfazl B

Reputation: 79

can everything be async in javascript?

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?

Upvotes: 0

Views: 1048

Answers (2)

sasy solutions
sasy solutions

Reputation: 179

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

Upvotes: -1

Jaromanda X
Jaromanda X

Reputation: 1

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

Upvotes: 2

Related Questions