How to Promisify this function - nodejs [duplicate]
Solution 1:
You have the error because create()
is not a Promise. Promisifying an async function is quite easy (nodejs has a built-in Promise support nowadays):
function createTicket(ticket) {
// 1 - Create a new Promise
return new Promise(function (resolve, reject) {
// 2 - Copy-paste your code inside this function
client.tickets.create(ticket, function (err, req, result) {
// 3 - in your async function's callback
// replace return by reject (for the errors) and resolve (for the results)
if (err) {
reject(err);
} else {
resolve(JSON.stringify(result));
}
});
});
}
// 4 - consume your promise with then() (resolved promise) and catch (rejected promise)
createTicket(ticket).then(function (result) {
// deal with result here
}).catch(function (err) {
// deal with error here
});
Solution 2:
rather than manually wrapping async code into promises, I would advice using libraries like Bluebird
to do that for you:
var Bluebird = require('bluebird');
//either
client.tickets = Bluebird.promisifyAll(client.tickets);
//or
client.tickets.createAsync = Bluebird.promisify(client.tickets.create);
...
return client.tickets.createAsync(ticket)
.then(JSON.stringify)
.catch(err => {
logger.error(error);
return false
});