简体   繁体   中英

callback of the callback function node js

So in Node we use async functions. And to do that we use callback functions as parameters. But how do I execute the final function after which I want to terminate the code? Just pass the empty function? Here's example:

fs.mkdir('stuff', function(){
    fs.readFile('readMe.txt', 'utf8', function(err, data) {
        fs.writeFile('./stuff/writeMe.txt', data);
    });
});

mkdir has callback function - all fine

readFile has callback function - all fine

writeFile has NOT callback function because that's the last thing I want to do, but then I get an error in console: "DeprecationWarning: Calling an asynchronous function without callback is deprecated."

Should I every time I do that, pass an empty function as a callback to avoid the error? What's the best practice for this?

Should I every time I do that, pass an empty function as a callback to avoid the error?

No.

What's the best practice for this?

Pass in a function and handle any errors it reports. You also need to handle errors from mkdir and readFile , which currently you're ignoring.

Eg:

fs.mkdir('stuff', function(err) {
    if (err) {
        // Do something with the fact mkdir failed
    } else {
        fs.readFile('readMe.txt', 'utf8', function(err, data) {
            if (err) {
                // Do something with the fact readFile failed
            } else {
                fs.writeFile('./stuff/writeMe.txt', data, function(err) {
                    if (err) {
                        // Do something with the fact writeFile failed
                    }
                });
            }
        });
    }
});

...which is a fair example of callback hell, which is part of the motivation of using promises instead. You could promisify the fs API (using any of several libs, such as promisify ) and do it like this:

fsp.mkdir('stuff')
.then(() => fsp.readFile('readMe.txt', 'utf8'))
.then(data => fsp.writeFile('./stuff/writeMe.txt', data))
.catch(err => {
    // Do something with the fact something failed
});

...where fsp is a placeholder for the promisified fs API.

In Node 8.x+, you could use async / await to write synchronous-looking code with those promisified APIs:

// This must be inside an `async` function
try {
    fsp.mkdir('stuff');
    const data = await fsp.readFile('readMe.txt', 'utf8');
    await fsp.writeFile('./stuff/writeMe.txt', data);
} catch (err) {
    // Do something with the fact something failed
}

You can use writeFileSync instead.

fs.mkdir('stuff', function(){
    fs.readFile('readMe.txt', 'utf8', function(err, data) {
        fs.writeFileSync('./stuff/writeMe.txt', data);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM