I am a long-time old school JS engineer, struggling with Promises. We are upgrading to HAPI v17, and I am having trouble figuring out how to convert the existing code to make it work. Here's the problem (generally):
I have a HAPI v16 route that does something like:
server.route({ method: 'GET', path: '/product/prd-{productId}/{filename*}', handler: function (request, reply) { var productId = encodeURIComponent(request.params.productId); if( /*someCondition*/ ){ server.inject('/staticmessages/product', function (SCResponse) { if (SCResponse.statusCode === 200 && SCResponse.statusMessage === 'OK') { productStaticContent = JSON.parse(SCResponse.payload).messages; } PDPController.renderPDP(request, reply, productId, productStaticContent); }); } else { PDPController.renderPDP(request, reply, productId, productStaticContent); } } });
Basically, the route handler checks some internal flags to determine if it needs to make an asynchronous call to retrieve some strings or not, then forwards control to a method on a controller object to fulfill the request.
So, I have a number of issues: First, is the conditional async call. Second, the server.inject call is now an await call (as of HAPI v17). Third, I need to return a Promise from the handler (whether I make the async call or not). Fourth, I guess the controller method has to be a promise?
I have reviewed (studied!) probably a dozen websites covering Promises, and a number of videos, and I guess it's really a paradigm shift, as I'm really not getting the full picture. Seems like it should be simple, but there's some unidentified hurdle I'm just not getting over. Any help would be much appreciated!
I'll write them using async/await
as
server.route({
method: 'GET',
path: '/product/prd-{productId}/{filename*}',
handler: async function (request, reply) { // put async
var productId = encodeURIComponent(request.params.productId);
const condition = await checkCondition(); // put await
if (condition) {
const SCResponse = await server.inject('/staticmessages/product'); // put await
if (SCResponse.statusCode === 200 && SCResponse.statusMessage === 'OK') {
productStaticContent = JSON.parse(SCResponse.payload).messages;
}
return PDPController.renderPDP(request, reply, productId, productStaticContent); // add return
}
return PDPController.renderPDP(request, reply, productId, productStaticContent);
}
});
Fourth, I guess the controller method has to be a promise?
Not necessary, we use async
for handler so it will always return promise.
Hope it helps