Greetings to all, please devote

Standard Application, NodeJS + ExpressJS, Default URL

//наш URL в браузере - http://localhost:12345/ //к нему шлем запросы app.post('/',function(req, res){ //объявляем переменную var count = 0; //считаем что то важное count = function_count_search();//sql запрос на ~20 секунд // .. тут оч. важные вычисления .. // .. а тут еще более важные вычисления .. //отдаем конечные данные res.end("~"+count+"~"); }); 

In general, the count variable is given as undefined. It is given faster than the sql query is executed. Well, of course you can use Kalbeki! Or? Only here in the examples from the Internet including. From this forum, all examples end inside a function, but I need to be able to operate the variable freely, and give it to res.end ()

Can this be done in NodeJS? If yes, please give an example code

Reported as a duplicate by members of Grundy , Pavel Mayorov , Duck Learning to Hide , user194374, Dmitriy Simushev 22 Feb '17 at 11:13 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Do not duplicate, because just indicated that the result is not needed in another function - serg
  • 3
    100% duplicate - you want to get the result from the asynchronous function, this is exactly what is described on the link - Grundy

1 answer 1

As an option to use promises.

 function_count_search() { return new Promise(function (resolve, reject) { /*... Ваши вычисления ...*/ resolve(count); } 

And in the controller

 app.post('/',function(req, res){ //объявляем переменную var count = 0; //считаем что то важное count = function_count_search();//sql запрос на ~20 секунд // .. тут оч. важные вычисления .. // .. а тут еще более важные вычисления .. count.then(function(counter) { //отдаем конечные данные res.end("~"+counter +"~"); }) }); 

A similar question was yesterday , I answered that req, res should be passed to a function and res.end ("~" + counter + "~"); and Dmitriy Simushev showed the promise option, which became the best