Skip to content

Instantly share code, notes, and snippets.

@vikaskanani
Last active April 29, 2024 06:12
Show Gist options
  • Save vikaskanani/5051a7f360357436aa459fd2183aa852 to your computer and use it in GitHub Desktop.
Save vikaskanani/5051a7f360357436aa459fd2183aa852 to your computer and use it in GitHub Desktop.
Code to demonstrate promisify any library if they don't return promises.
var client = inbox.createConnection(config);
client.on('connect', function () {
client.openMailbox('INBOX', function (err, info) {
if (err) {
console.error('Box open error', err);
} else {
console.log('Message count in INBOX : ' + info.count);
client.listMessages(0, 1, function (err, messages) {
if (err) {
console.error('Message Listing error', err);
client.close();
} else {
//read messages
client.close();
}
});
}
});
});
client.on('error', function (err) {
console.error('Connection error', err);
});
client.connect();
///////////////////////////////////////////////////////////////////////
async function listMessages(client){
return new Promise((resolve, reject) => {
client.listMessages(0, 1, function (err, messages) {
if (err) {
reject(err);
} else {
resolve(messages);
}
});
});
}
async function openMailbox(client){
return new Promise((resolve, reject) => {
client.openMailbox('INBOX', function (err, info) {
if (err) {
reject(err);
} else {
resolve(info);
}
});
});
}
async function ClientConnect(client){
return new Promise((resolve, reject) => {
client.on('connect', function () {
resolve();
});
client.on('error', function (err) {
reject(err);
});
client.connect();
});
}
async function main() {
try {
var client = inbox.createConnection(config);
await ClientConnect(client);
const info = await openMailbox(client);
if ( info.count > 0 ) {
const messages = await listMessages(client);
} else {
//log
}
client.close();
} catch (err) {
console.error(err);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment