Y
Y
Yuri Ivanov2022-04-16 20:30:21
Node.js
Yuri Ivanov, 2022-04-16 20:30:21

How to execute functions synchronously?

Hello, please help me deal with nodes. I wrote some Javascript code, it is executed from top to bottom, everything is super clear. In a node with asynchrony, there is some other world. I can’t fully understand and figure out how I can perform actions in the node gradually, in order
, let’s say I do

let data = []
const fs = require('fs/promises');
fs.readFile('./data.txt', 'utf8', 
    async (error, d) => {
      if (error) throw error;
      data = await JSON.parse(d)

Or I can work with files synchronously by adding Sync at the end
. And how to run functions synchronously in a node, I have functions that work with one file, read it, write something, delete it. If the functions are executed all together, then as I understand it, I may have inaccuracies in the file entry.
I had an idea to use promise all, but inside promise all the functions are also executed asynchronously The
question is how can I run fnOne, fnTwo, wait for them both to work, and then run fnThree
I honestly googled, I even watched Timur Shemsedinov's lecture, but before I don't get that moment

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Goretsky, 2022-04-16
@asvici

What prevents you from doing this through the usual await?:

async function fnOne() {
  return new Promise(res=>setTimeout(()=>{res(1000)}, 1000))
}
async function fnTwo() {
  return new Promise(res=>setTimeout(()=>{res(2000)}, 1200))
}
async function fnThree() {
  return new Promise(res=>setTimeout(()=>{res(3000)}, 1400))
}

const allFn = async ()=>{
  try {
    await fnOne()
    console.log('Выполнилась 1-я ф-ция')
    const rz = await fnTwo()
    console.log('Выполнилась 2-я ф-ция, полученный результат = ', rz)
    await fnThree()
    console.log('Выполнилась 3-я ф-ция')
  }catch (e) {
    console.error(e)
  }
}

allFn()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question