Answer the question
In order to leave comments, you need to log in
How to work with asynchronous module?
There is a module that makes a request to the database. I call it from another place, but due to asynchrony, it does not have time to work out. How to call it synchronously?
function createExtraData() {
var regionList = regionsLists.getRegionsList();
console.log(regionList) //Тут undefined, запрос к базе в модуле еще не успел выполнится
sendData()
}
Answer the question
In order to leave comments, you need to log in
All through callbacks!
In the getRegionsList parameters, pass a callback in which you will already perform actions with the received data.
Asynchronous functions usually don't return anything (via return). Their task is to call a callback and pass the result of the function execution into it (in your case, a query to the database).
UPD: example (your module)
//...
module.exports.getRegionsList = function(callback)
{
/*абстрактный пример запроса к БД*/
db.req(callback);
/*
Предполагается что функция req асинхронная и так же принимает callback.
Передаете в неё параметр вашей функции. Формат вашего callback'а определяется сигнатурой callback'а в req
*/
}
You need to come up with something like this:
How to do it: https://learn.javascript.ru/promise
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question