A
A
amg04612021-07-28 23:14:19
Node.js
amg0461, 2021-07-28 23:14:19

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
}

Naturally, what is written will not work , because return will not wait for the non-blocking call to complete and will work immediately . How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-07-28
@amg0461

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 question

Ask a Question

731 491 924 answers to any question