Home > Software engineering >  How to properly return a value from a callback within a Promise?
How to properly return a value from a callback within a Promise?

Time:02-26

I know that very similar questions have been asked, but I can't find one that fits my issue exactly- feel free to point me that way if there is one.

sendSteamAuthTicket: () => {
    return new Promise((resolve, reject) => {
        greenworks.getAuthSessionTicket(function(ticket) {
            console.log('Successfully retrieved Steam API User Auth Ticket.')
            console.log(ticket.ticket.toString('hex'))
            resolve(ticket.ticket.toString('hex'))
        }, function(e) { throw e })
    })
}

Basically, this returns an endlessly pending Promise, leading me to believe I can't resolve a Promise from within a nested callback like this. Unfortunately, I can't send the data via an additional function because electron won't let you interface with the browser that way.

Is it possible to do what I'm trying to do here? e.g. more or less obtain a delayed Promise value within this single function?

CodePudding user response:

Alright, I figured it out- sorry for the redundant question, I've been banging my head on this for a few hours. Hearing that the Promise syntax was correct was apparently enough to get it through.

The greenworks package was being imported incorrectly (or, rather, correctly- according to their docs- but needed a direct file path)

It's a little outdated so I wasn't sure why at first.

CodePudding user response:

There's nothing wrong with the way that you're calling resolve. If the callback is called, resolve will be, too, unless ticket is null or similar. My guess would be that greenworks is calling the error callback and then not re-throwing your thrown error. Try doing reject(e) instead of throw e.

  • Related