I am runnig the code below in a .ts file in the Next API Folder.
I am trying to wait the result of a call to an unofficial API of Reverso (https://www.npmjs.com/package/reverso-api).
The problem is that the code below continues to wait the request even if the the response from reverso has arrived and the value has been updated.
How can I can I do?
The reverso.getContext('Dog', 'English', 'German', ... ) method returns a Promise.
type Data = {
responseWord : string
}
let r = 3;
export default async function handler( req: NextApiRequest, res: NextApiResponse<Data>) {
const Reverso = require('reverso-api');
const reverso = new Reverso();
console.log("1");
await reverso.getContext('Dog', 'English', 'German', (response : any) => {
r = response?.text;
console.log(r);
return;
}).catch((err : any) => {
});
console.log("2");
res.status(200).json({ responseWord : `${r}` });
}
reverso.getContext() can be used in both ways, by using the callback based approach, or using promises, since it returns a promise. The correct way to retrieve the response data using an async function is this:
const Reverso = require('reverso-api');
const reverso = new Reverso();
export default async function handler( req: NextApiRequest, res: NextApiResponse<Data>) {
try {
const { text } = await reverso.getContext('Dog', 'English', 'German');
res.status(200).json({ responseWord : `${text}` });
} catch(e){
console.log(e)
}
}
The callback based version:
const Reverso = require('reverso-api');
const reverso = new Reverso();
export default function handler( req: NextApiRequest, res: NextApiResponse<Data>) : void {
reverso.getContext('Dog', 'English', 'German', (response : any) => {
res.status(200).json({ responseWord : response?.text });
}).catch((err : any) => {
console.log(err)
});
}