1

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)
} 
7
  • 1
    What is the somehow logic to populate the array and what is the promise library you are using? Commented Nov 28, 2016 at 23:00
  • I tried with native Promise object. I tried with some code and didn't work. Commented Nov 28, 2016 at 23:02
  • You cannot write your own asynchronous functions. You have to use an already-async function such as setTimeout Commented Nov 28, 2016 at 23:02
  • Yes, but I understand that if I use setTimeout I will just execute the same function X seconds later and still will block the code. Is it impossible to async populate the array AND at the same time continue with the execution with of the rest of the code ? Commented Nov 28, 2016 at 23:04
  • Can you post the logic you had with the native async? Commented Nov 28, 2016 at 23:06

1 Answer 1

3

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
    });
} 
Sign up to request clarification or add additional context in comments.

2 Comments

It seems this works exactly as I want, thanks ! Can you explain how exactly the flow goes with setTimeout equals 0 ?
setTimeout will have it's own call stack and runs right after the current stack is cleared. Just remember that JS in browser is single threaded, so it's still blocking

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.