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)
} 
gneric
  • 3,457
  • 1
  • 17
  • 30
  • 1
    What is the somehow logic to populate the array and what is the promise library you are using? – Aruna Nov 28 '16 at 23:00
  • I tried with native Promise object. I tried with some code and didn't work. – gneric Nov 28 '16 at 23:02
  • You cannot write your own asynchronous functions. You have to use an already-async function such as `setTimeout` – Bergi Nov 28 '16 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 ? – gneric Nov 28 '16 at 23:04
  • Can you post the logic you had with the native async? – Aruna Nov 28 '16 at 23:06
  • I tried something like this: `function populateAsync(arr) { var p = new Promise(function(resolve, reject) { while (arr.length <= 100000000) { arr.push(1); }; resolve(); }); }` – gneric Nov 28 '16 at 23:07
  • Possible duplicate of [How to make non-blocking javascript code?](http://stackoverflow.com/questions/26615966/how-to-make-non-blocking-javascript-code) – gneric Nov 28 '16 at 23:25

1 Answers1

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
    });
} 
nottu
  • 369
  • 1
  • 12
  • It seems this works exactly as I want, thanks ! Can you explain how exactly the flow goes with setTimeout equals 0 ? – gneric Nov 28 '16 at 23:12
  • 1
    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 – nottu Nov 28 '16 at 23:19