Answer the question
In order to leave comments, you need to log in
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
Your first res.send
sends all the headers and the body, which ends the entire request-response process and closes the ability to use the current object res
to send anything. In this case, you need to remove the first call from the code res.send
and 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.
Use koa
router.get('/', async ctx => {
ctx.body = await collection.find().toArray(); // при условии, что это вернет promise
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question