How to export the contents of a promisse that is in a module to another module?

Asked

Viewed 62 times

0

I have the following module getToken.js:

var rp = require('request-promise');

const options = {
    url: 'https://meuservidor:8080/nifi-api/access/token',
    method: 'POST',
    gzip: true,
    rejectUnauthorized: false,
    headers: {
        'Accept-Encoding': 'gzip, deflate, br',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: 'username=meuusuario&password=minhasenha'
}

rp(options)
    .then(function(body) {
        console.log(body)
    })
    .catch(function(err) {
        console.log(err)
    })

How to export content from console.log(body) to another module?

  • 1

    You just need to call rp() once and you want to export the value of body or you want to call rp of other modules and receive bodys different?

  • I only need to call Rp() once and I want to export the body value

1 answer

0

In short, you cannot export the resolution (or rejection) value of the promise. To learn more about why, read this answer. Thus, an option is to export the Promise, and use the then and/or catch in the module that imports it.

So, in the module you export, you must export to Promise. Therefore:

// ...

// `rp` é uma função que retorna uma `Promise`.
module.exports = rp();

And to import:

const bodyPromise = require('./my-module.js');

bodyPromise.then((body) => /* Do stuff. */); // Não se esqueça do `catch`. :-)

Another option would be to export the function rp, using module.exports = rp. However, this would make you have to call this function in the modules that import it. By always exporting the Promise (the value returned by the function), you assume the argument passed options will always be the same. If this is not what you need, you should export the function, not your return-the promise.

  • I was only able to reproduce what I wanted in python, so: http://dontpad.com/oqfizempython

  • Python is a language. Javascript is another. Because modules in Javascript work synchronously, you cannot wait for the promise to resolve to export a value. Language won’t always do what you need it to do... You should look for some way to solve according to the "limitations" (if that is one) of the language. One way to do this is to export the promise directly.

  • Also, I don’t know how to program in Python, but I believe you managed to do in Python because the methods you used in Python are synchronous (I think they are), which is not the case in Javascript... If it’s still not what you need, edit your question by adding more details so I can help you better. :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.