-2

I have a function that contains a promise. The function do an HTTP request and I want to resolve it and return the response as a value in a variable.

function sendCommand(auth, playerId, command) {
    return new Promise((resolve, reject) => {
        request.post(`https://test.com/${playerId}/command`,{
            headers: { Authorization: auth },
            json: {
                "arg": `${command}`
            }
        }, function status(err, response, body) {
            if (response.statusCode === 200) {
                resolve(body)
            } else {
                reject(err)
            }
          }
        )  
    })
}

I run this function from a different file so I do the following:

module.exports = {
    doSomething: (playerId, command) => {
        loginHelper.getToken().then(token =>
        sendCommand(token, playerId, command))
    }
}

On the other file, I want to store the resolved response in a variable such as this:

const commandHelper = require(__helpers + 'command-helper')

let test = commandHelper.doSomething(playerId, 'command')

I expect the test variable to contain response data.

  • 3
    You don't. You have to be asynchronous the whole way down. – zero298 Sep 06 '18 at 16:01
  • 1
    Promises are 'viral', there's no way to unwap them so once you start using them (and you often *have* to start using them) you just keep using them. Return the Promise from `doSomething` and `.then` do something else. – Jared Smith Sep 06 '18 at 16:03

1 Answers1

1

You should use await in async function Example:

function hi(){
  return new Promise((res,rej)=>{
       res("hi");
   }
}
async function see(){
   var hiStr = await hi();
   console.log(hiStr); // hi
}
cemsina güzel
  • 390
  • 4
  • 14