U
U
Urukhayy2016-10-31 06:27:28
JavaScript
Urukhayy, 2016-10-31 06:27:28

How to "bypass" asynchrony in this example?

On a GET request, you need to receive data from MongoDB and send it as a response.
The following code example throws an error when calling res.send() from a callback:

app.get("/", function(req, res) {
      res.send("Hello"); // Данный вызов выполняется
      collection.find().toArray(function(err, items) {
    res.send("Hello 2"); // Данный вызов не выполняется (Неизвестный метод send)
  });
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
Faliah, 2016-10-31
@Urukhayy

Your first res.sendsends all the headers and the body, which ends the entire request-response process and closes the ability to use the current object resto send anything. In this case, you need to remove the first call from the code res.sendand you will get "Hello 2". You don't need any asynchrony bypasses, global variables, etc. The res variable will be available inside the callback as long as you don't override it somewhere in the scope.

A
Anton, 2016-10-31
@SPAHI4

Use koa

router.get('/', async ctx => {
  ctx.body = await collection.find().toArray(); // при условии, что это вернет promise
});

R
Rou1997, 2016-10-31
@Rou1997

The fact is that you function(err, items)do not pass to the function res, there are two ways to get around, the first - simple - to declare globally, breaking the entire asynchrony of anonymous functions, and the second - correct, as here for XMLHttp.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question