I am trying to make a call to extranet which should return me a parameter but the api doesn't await for it.
Orders.prototype.add = function (data, db, callback, logger) {
var extranet = new API_EXTRANET();
extranet.addOrder(data, function(err, orders) {
if (!err) {
if(callback) callback(false, orders);
}else{
if(callback) callback(err, false);
}
}, logger);
};
I tried to return a Promise of it but nothing happens.
Orders.prototype.add = function (data, db, callback, logger) {
var extranet = new API_EXTRANET();
return new Promise((resolve, reject) => {
extranet.addOrder(data, function(err, orders) {
if (err){
reject(err)
} else {
resolve(orders)
}
})
})
};
Here is where I call the method:
order.addStoreOrder(order_data_update, db).then((response) => {
order.add(array_data, db, function (err, order_response) {
You are mixing different way to handle asynchronous calls : callback and promises. You should stick to promises only.
// There is no need for callback here, the promise replace your callback
// Because you use of await I guess you should use it here as well
Orders.prototype.add = async (data) => {
const extranet = new API_EXTRANET();
return util.promisify(extranet.addOrder)(data);
};
// How to call it
try {
const orders = await order.add(arrayData);
} catch (err) {
// Handle the error
}
In case you want to wrap the addOrder
return, you can do :
Orders.prototype.add = async(data) => {
const extranet = new API_EXTRANET();
try {
const orders = await util.promisify(extranet.addOrder)(data);
console.log(orders);
return orders;
} catch (err) {
console.error(err);
throw new Error('custom error');
}
};
// How to call it
try {
const orders = await order.add(arrayData);
} catch (err) {
// Handle the error
}
Documentation: util.promisify()
Description: It turns a function that use callbacks into a Promise function