S
S
Sashqa2020-03-04 16:49:50
Node.js
Sashqa, 2020-03-04 16:49:50

How to push data to the top in node js?

// server.js

import { sendHttpRequest } from "../../../api";
import { checkFiles } from "../../../api";

app.get('/', ((req: any, res: any) => {
    // тут я вызываю какой-то метод
    sendHttpRequest(num1, num2)
}))

// В файле sendHttpRequest.js я отправляю запрос и  вызываю еще один метод

export sendHttpRequest = async (num1, num2) => {
    try {
        await fetch(id, param)
            .then((response: any) => response.json())
            .then(data => {
                checkFiles(id, data);
            })
    }
    catch (e) {
        console.error(e)
    }
}

in checkFiles.jsI make a few other queries and at the output I somehow get a result that I need to throw to the very top - in in server.jsorder to get in reponse? that is , res should be my result. How can this be achieved? app.get('/', ((req: any, res: any)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-03-04
@Sashqa

General Approach

app.get('/', (req, res, next) => {
  sendHttpRequest(num1, num2)
    .then(data => anyFetch1(url))
    .then(data => anyFetch2(url))
      ....
    .then(data => res.json(data))  // ответ клиенту
    .catch(err => next(err)) // ошибка 
.then
}))

sendHttpRequestand each anyFetch- must return a promise.
PS
You don't have a return in your code
return await fetch(id, param) // return !!!
         .then((response: any) => response.json())
            .then(data => {
              return  checkFiles(id, data); // return надо ставить 
            })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question