Skip to content

Instantly share code, notes, and snippets.

@saibotsivad
Created November 5, 2016 04:26
Show Gist options
  • Save saibotsivad/318ec24d864e4d9a41887b02ef9d181f to your computer and use it in GitHub Desktop.
Save saibotsivad/318ec24d864e4d9a41887b02ef9d181f to your computer and use it in GitHub Desktop.
resolve promise outside of promise

IMAP connections are like this:

  • send a message prefixed with a session-unique number
  • on data, the string will have a prefix that is the number of the thing it's responding to
  • there is no guarantee the responses will be in any order
// the basic idea
function connect() {
const map = {}
const connection = makeConnection()
connection.on('data', data => {
const id = parseId(data)
map[id].resolve(data)
})
connection.on('end', () => {
Object.keys(map).forEach(id => map[id].reject('end'))
})
return function write(message) {
const id = generateUniqueId()
return new Promise((resolve, reject) => {
map[id] = { resolve, reject }
})
}
}
// using it
const messenger = connect()
messenger('some command')
.then(data => dataHandlerFunction)
.catch(error => errorHandlerFunction)
// the basic idea
function connect() {
const emitter = new EventEmitter()
const connection = makeConnection()
connection.on('data', data => {
const id = parseId(data)
emitter.emit(id, data)
})
return function write(message) {
const id = generateUniqueId()
return new Promise((resolve, reject) => {
emitter.on(id, data => resolve(data))
})
}
}
// using it
const messenger = connect()
messenger('some command')
.then(data => dataHandlerFunction)
.catch(error => errorHandlerFunction)
@rogerweb
Copy link

rogerweb commented Aug 1, 2017

Hi Tobias,

I'm trying to implement a similar logic and ended up finding your gist, but couldn't make it work. Were you able to resolve a promise from outside the promise? Would you have an example?

Thanks,

Roger

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment