F
F
fon_harry2018-05-22 13:38:38
JavaScript
fon_harry, 2018-05-22 13:38:38

JavaScript how to run synchronous code asynchronously?

I want to read two files synchronously. But do it asynchronously. Files of different sizes, which is reflected in the names. This is necessary for understanding how asynchronous calls work. But I can't.

let fs = require('fs')

function read (file, callback) {
  fs.readFileSync(file, 'utf8')
  setTimeout(() => {
    callback(file)
  }, 0)
}

console.log('start')

read('big.txt', (result) => {
  console.log('file', result)
})

read('small.txt', (result) => {
  console.log('file', result)
})

console.log('end')

Result:
start
end
file big.txt
file small.txt

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Interface, 2018-05-22
@Interface

function read (file, callback) {
  const result = fs.readFileSync(file, 'utf8')
  setTimeout(() => {
    // обычно первым аргументом у callback'ов ошибка или null если все ок
    callback(null, result)
  }, 0)
}

try like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question