I have a function that performs long computation and once done invokes a callback function that is passed as parameter.
I am querying this function within Koa router and need to return to the browser the results of long computation. Function comes from a library and I am not able to change its interface (i.e. I can change the code of the callback but I can't change someLongComputation
to return a promise)
Current code sets ctx.body
immediately as someLongComputation
returns immediately. Any idea how I can wait until the callback is called and only then set the ctx.body
with the results from the callback.
router.post(`/abc`, async (ctx) => {
try {
someLongComputation(function(err, res) {
if(err) {
console.log(err);
}
}
ctx.body = {
status: 'success',
data: {'res' : ""},
errors: []
};
} catch (err) {
console.log(err)
}
})
someLongComputation()
to use a promise:require('util').promisify(someLongComputation)
returns a version of the function you canawait
. – Patrick Roberts