asked on
nodejs async code with functions that use callbacks and do not return promises
i am struggling to understand nodejs asynchronous code better
consider the function fs.realpath() which does not return a promise and expects a callback
Q1 : is there a variant of the func that i can call simply with
realpath = async realpath(whatever)
Q2 : is there a generic way to allow async code to run in the callback. i assume with promisify
await promisify(fs.realpath(whatever,(err,function(){
// do something using async here
})))
Q3 : is there some kind of trivial hack that will allow to set a variable in the parent scope within the callback while preserving async scopes properly. i do not really care if the call is blocking but if it can be asynchronous all the better.
var path
fs.realpath(whatever,(err,function(){
// set the path here
}))
// do something using path here
i must admit i read the documentation but the learning curve is rather huge. i am rather familiar with all kinds of asynchronous programing including event driven but the nodejs way is still quite blurry
thanks a lot for your help
You can simulate this with some odd code + net result is the same, you're forcing async code to run synchronously, so just nullified the async function.
ASKER
the goal is to get a return value rather than a callback
this is actually handled quite nicely by promisify
promisifying the func actually allows to omit the callback
"async" was a typo for "await" my bad
rp = await realpath(p).catch((error) => { console.log(error) })
if(rp === undefined)return
console.log(rp)
ortry {
rp = await realpath(p)
console.log(rp)
}catch(e){console.log(e)}
the catch block may be omitted as long as the whole thing is itself in some catch blocki see no way to handle the error outside of a catch block
anyone who is interested may dig deeper using new promise and resolve but my attempts merely produced at best the same results with a much more complex syntax
---
Q3 has an easy answer in global scope
but this won't help here since the callbacks are ALWAYS run asynchronously which i was totally missing
ASKER
ASKER
this works for Q2
i would be happy to know if there is anything simpler or something i might be missing that would mess the scopes if i use this syntax
const realpath=util.promisify(myfunc)
await myfunc("PARAMETER", async function (err,url){
// async code here
})