A
A
AlexZeDim2018-03-01 15:45:25
JavaScript
AlexZeDim, 2018-03-01 15:45:25

Export promise/async function (result) of node.js via module.exports?

Hey!
And so, a question that probably comes up with every new version of JS and almost everyone who has come across something asynchronous on node.js.
There is a module code (briefly):

function имя1 (параметр_из_формы) {
        request (параметры)
            .then(response => {
                let charset = [];
                charset.name = response.data.
                //здесь код, который что-то делает
                return (charset);
            })
            .then(charset => {
                if (charset.value=== undefined) {
                    charset.value= 'PR10';
                } else {
                    charset.guild = charset.guild.name;
                }

                return charset; //то, что мне надо получить в app.js
            })
            .catch(function (error) {
                console.log('ошибка')
            });
    }
module.exports = имя1

And there is app.js where we have mongoDB via mongoose:
const trade_log = require("./db/models/trade_log");
const имя1 = require("./db/ops/модуль");
app.all('/log', function (req, res, next) { //это у нас Express
    let x = имя1(req.body.Counterparty); //вот здесь у меня проблема
    trade_log.create({ //тут мы пишем в базу
        Flag: req.body.Flag,
        Instrument: req.body.Instrument,
        Venue: req.body.Venue,
        Price: req.body.Price,
        Currency: req.body.Currency,
        Quantity: req.body.Quantity,
        Counterparty: req.body.Counterparty,
        Identifier: x,
        Commentary: req.body.Commentary,
    },function (err, res) {
        if (err) return console.log (x) + handleError(err);
        console.log(res);
    });
    next();
});

The problem is that I can't export the result of the function itself and write it to a variable. After a day of Google coding, as I understand it, this is a problem that lies in the plane of async / await functions and promises. Because. when I try (and tried before) to export a function from my module, I get this. what:
  • or x returns 'undefind' i.e. it is obvious that the code executes perfectly on its own, just because of the asynchrony, the response to the request arrives longer than it goes to drink in MongoDB and the variable does not have time to be written
  • or an error occurs in the console that name1 is not a function.

I know for sure that the code itself is written correctly and correctly, and independently of each other it executes correctly. Actually, in addition to the toster, I already googled enough and realized that I need to either sign the module for promises (which I tried to do several times, but it didn’t work out well for me) or use ES7 i.e. async/await, which is quite simple and interesting, but for some reason similar code in app.js did not stop execution where necessary:
app.all('/log', async function (req, res, next) { //это у нас Express
    let x = await имя1(req.body.Counterparty)

The sequence of actions, as it should be:
  1. I receive data in POST through the form,
  2. The function from the module takes the value from the field as a parameter and sends an http request
  3. The result comes back (and/or is written to a variable)
  4. All data is written to the database

And it turns out that step 4 happens before step 3

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Coder321, 2018-03-01
@Coder321

Something like this

module.exports = async function имя1(params) {
    try {
        const response = await request(params);
        let charset = [];
        charset.name = response.data;
        const charsetResult = await someFunc(charset);
        if (charsetResult.value === undefined) {
            charsetResult.value = 'PR10';
        } else {
            charsetResult.guild = charset.guild.name;
        }
        return charsetResult;
    } catch (error) {
        console.log(error);
    };
}

V
Vladimir Skibin, 2018-03-01
@megafax

It seems that everything is simple.

function имя1 (параметр_из_формы) {
return request (параметры) /*****/ 
}

...
let x = имя1(req.body.Counterparty)
           .then(() => trade_log.create({/***/}));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question