V
V
VladVol2017-05-06 21:45:59
JavaScript
VladVol, 2017-05-06 21:45:59

Is the code asynchronous?

Is code that uses synchronous methods wrapped in a Promise asynchronous?

function fn(id){
   return new Promise((resolve, reject) => {
      let data = fs.readFileSync('file' + id + '.txt', 'utf-8');
      resolve(data);
   });
}

for(let i = 0; i < 1000; i++){
   fn(i);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VladVol, 2017-05-06
@VladVol

Reading the file takes some time, no? So, this example with a random delay is more correct

function fn(id){
   return new Promise((resolve, reject) => {
      setTimeout(() => {
    	console.log(id);
    resolve(id);
    }, Math.random() * 1000);
   });
}

for(let i = 0; i < 100; i++){
   fn(i);
}

So asynchronous.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question