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) |
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