Cannot get async await to work
arelstone opened this issue · 2 comments
I found this lib and it seems very promising. Promising leads me to my issue ;P I'd like to use async/await and cannot get it to work.
I got a Node api with express and typescript and I would like to use async/await for awaiting the data from my profile-service:
It works fine if I do not use async/await and use a callback instead. If I implement async/await it seems like my api just times out.
What I'd like to do is send an event profile:get
, await the data and send the response to the user.
It seems like the issue is not the Profile service
but lies in the api-service. I am sure that there is something simple that I am overseeing
Profile service
const { Responder } = require('cote');
new Responder({ name: 'Profile Service' })
.on('profile:get', ({ payload }, cb) => {
cb(`Hello from Profile! Payload: ${payload.id}`);
});
Api routes:
This works:
app.get('/profile/:id', (req: Request, res: Response) => {
client.send({
type: 'profile:get',
payload: { id: req.params.id }
},
(response) => {
res.send(response).status(OK);
});
});
This Doesn't work:
app.get('/profile/:id', async (req: Request, res: Response) => {
const profile = await client.send({
type: 'profile:get',
payload: { id: '42' },
});
res.json({ profile }).status(OK);
})
Hello 👋 the issue here is mixing and matching async/await with callbacks. If you use a promise in Profile service instead of a callback, it’s going to work. Let us know if this helps.
@dashersw Thanks a lot...
Changing my profile service to use a promise works.
I knew that there were something very simple that i'd didn't see :)
const { Responder } = require('cote');
new Responder({ name: 'Profile Service' })
.on('profile:get', ({ payload }) => {
return Promise.resolve(`Hello from Profile! Payload: ${payload.id}`);
});
I think that think issue can now be closed