E
E
Elena2020-08-12 16:49:10
JavaScript
Elena, 2020-08-12 16:49:10

Where is it better to use promises and not callbacks?

People, where is it better to use promises and not callbacks?

app.use('/', (req, res) => res.status(404).send({ message: 'Запрашиваемый ресурс не найден' }));

router.get('/', (req, res) => {
  readerFunction(usersPath, res).on('open', () => {
    res.writeHead(200, { 'Content-type': 'application/json; charset=utf-8' });
    readerFunction(usersPath, res).pipe(res);
  });
});

router.get('/:id', ((req, res) => {
  readerFunction(usersPath, res).on('open', () => {
    const users = jsonParse(usersPath);
    const user = users.find((item) => item._id === req.params.id);
    if (!user) res.status(404).send({ message: 'Нет пользователя с таким id' });
    res.send(user);
  });
}));

const readerFunction = (fileName, res) => {
  const reader = fs.createReadStream(fileName, { encoding: 'utf8' });
  reader.on('error', () => {
    res.status(500).json({ error: 'На сервере произошла ошибка' });
  });
  return reader;
};
const jsonParse = (fileName) => JSON.parse(fs.readFileSync(fileName, { encoding: 'utf8' }));

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question