gneric
gneric

Reputation: 3725

javascript async populate array

I want to understand how to write my own async functions.

So how can I populate the array with a lot of elements async and see 'finish' line without delay, instead of waiting the population to complete ?

Here is the example of which I tried to implement Promises and callbacks but didn't succeed.

let arr = [];

populateAsync(arr);
console.log('finish');

function populateAsync(arr) {
    // somehow populate arr async till it reaches
    // 100000000 elements (big enough to make a delay)
} 

Upvotes: 1

Views: 3305

Answers (1)

nottu
nottu

Reputation: 379

You can use a Promise object or just use a setTimeout()

let arr = [];
populateAsync(arr);
console.log('finish');

function populateAsync(arr) {
    setTimeout(function(){
        //do something
    },0)
} 

with Promise

let arr = [];
populateAsync(arr).then(function(){//do something with arr
});
console.log('finish');

function populateAsync(arr) {
    return new Promise(function(resolve, reject){
        //do something
        resolve(arr); //resolve with value
    });
} 

Upvotes: 3

Related Questions