我将node.jsBundle 在一起,但不能理解为什么一个文件可以工作,而另一个文件不能
你能给我解释一下为什么吗 这是可行的:
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('note')
.deleteOne(details)
.then((result) => res.send(result))
.catch((err) => {
!error.logged && logger.error('Mongo error', err);
error.logged = true;
throw err;
});
});
但是这永远不会进入回调函数,并停留在deleteOne中,但是在db中我们看到条目被删除了.
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('note').deleteOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send('Note ' + id + ' deleted!');
}
});
还有,我看到的所有例子,他们说下面的代码应该可以工作,但它从来没有进入回调,它确实建立了数据库连接,我可以在数据库日志(log)中看到
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
console.log("hello");
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
console.log("bye");
我到底遗漏了什么,还是我的系统有问题?
下面是一个非常简单的来自chat gpt Works的回调示例
const fs = require('fs');
// Function to read a file asynchronously and invoke a callback when done
function readFileAsync(filePath, callback) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
callback(err, null); // Pass the error to the callback
} else {
callback(null, data); // Pass the data to the callback
}
});
}
// Example usage of the readFileAsync function
const filePath = 'example.txt';
readFileAsync(filePath, (err, data) => {
if (err) {
console.error('Error reading the file:', err);
} else {
console.log('File content:', data);
}
});
为什么内置回调不起作用?