gpt4 book ai didi

node.js - fs.unlink 中会先执行路径还是回调?

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:02 24 4
gpt4 key购买 nike

我是 Node.js 新手,我不明白 fs.unlink() 的文档功能:

The asynchronous form always takes a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception.If the operation was completed successfully, then the first argument will be null or undefined.

const fs = require('fs');

fs.unlink('/tmp/hello', err => {
if(err) throw err;
console.log('successfully deleted /tmp/hello');
});

哪个参数将首先执行 - 回调还是路径?为什么第一个参数被保留用于异常?

最佳答案

这是 Node.js I/O API 函数的常见模式。如果你这样编写代码可能会更容易理解

const fs = require('fs');

var resultHandler = function(err) {
if(err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}

console.log("about to call unlink");
fs.unlink('/tmp/hello', resultHandler);
console.log("called unlink");

执行此代码后,您将看到它打印出来

about to call unlink
called unlink
file deleted (or unlink failed if operation ecountered an error)

回调函数resultHandler由Node.js API在I/O操作完成后调用,这可能在调用API函数后很长时间内发生。回调函数的第一个参数是err,如果没有错误,则为 null,否则有错误消息。

关于node.js - fs.unlink 中会先执行路径还是回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com