J
J
jtag2018-02-11 20:32:17
JavaScript
jtag, 2018-02-11 20:32:17

How to return values ​​from a module from an asynchronous function?

module.exports.person = function(){
    (async function foo(){
        let data = '';
        data = await sqlQuery();

    }());

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
levchak0910, 2018-02-11
@msa6886

Module:

exports.getPerson = function(id) {
    return new Promise((resolve, reject) => {
        // Любая асинхронная операция. Например:
        sql.query(`select * from users where id='${id}'`, data => {
            // Если запрос произошел успешно
            resolve(data);
        }, error => {
            // Если с ошибкой
            reject(error);
        });
    });
};

We use it where necessary:
let {getPerson} = require("path/to/module");
let person = await getPerson('some id');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question