Answer the question
In order to leave comments, you need to log in
How to return the result of a non-blocking call?
There is an API function that does a simple thing: it tries to open a file and returns its contents if successful, and returns the string "none" if it fails. I know how to write it with promises and async/await. And how to write it without promises , with a regular callback? Before the invention of promises, they somehow wrote something like this ... There must be something like
const api = () => {
fs.readFile(fileName, (err, content) => {
if (err) {
// api должно вернуть строку "none"
} else {
// api должно вернуть content
}
})
return // либо "none", либо content
}
Answer the question
In order to leave comments, you need to log in
I know how to write it with promises and async/await. And how to write it without promises, with a regular callback? Before the invention of promises, they somehow wrote this ...api can also have a callback that can be called when the result of the operation is ready
const api = (cb) => {
fs.readFile(fileName, (err, content) => {
if (err) {
cb("none")
} else {
cb(content)
}
})
// return не нужен
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question