D
D
Danil2016-05-31 11:35:27
JavaScript
Danil, 2016-05-31 11:35:27

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()
}

Can I get a code example how to fix it? I read about promises but I don’t understand how they will be used here.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tex0, 2016-05-31
@Veneomin

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
*/
}

D
Dmitry Eremin, 2016-05-31
@EreminD

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 question

Ask a Question

731 491 924 answers to any question