This question already has answers here:
How do I access previous promise results in a .then() chain?
(17个答案)
6个月前关闭。
我想在NodeJS中为MongoDB使用Promise。因此,我有一些代码:
然后将
但是此脚本调用错误:TypeError:无法读取未定义的属性“ close”。
你能帮我吗?如何解决这个问题?
您还可以通过所有
(17个答案)
6个月前关闭。
我想在NodeJS中为MongoDB使用Promise。因此,我有一些代码:
const mongo = require('mongodb').MongoClient;
const config = require('./config.json');
mongo.connect(config.URI, function (err, client) {
const db = client.db("INDFLORIST");
const collection = db.collection('API');
collection.insertOne({name: 'Roger'}, function (err, res) {
if (err) throw err;
console.log("Document inserted");
client.close();
});
});
然后将
callback
转换为promise
:const mongo = require('mongodb').MongoClient;
const config = require('./config.json');
mongo.connect(config.URI).then(client => {
const db = client.db("INDFLORIST");
const collection = db.collection('API');
return collection.insertOne({name: 'Roger'});
})
.then(function(result) {
console.log("Document inserted");
}).then(client => {
client.close();
})
.catch(err => {
console.error(err);
});
但是此脚本调用错误:TypeError:无法读取未定义的属性“ close”。
你能帮我吗?如何解决这个问题?
最佳答案
您可以创建一些外部变量_client_
,并在成功连接后为它分配client
,然后可以使用_client_
在上一个then
回调中关闭连接。
const mongo = require("mongodb").MongoClient;
const config = require("./config.json");
let _client_; // <-- external variable
mongo.connect(config.URI).then(client => {
_client_ = client; // <-- assing real client to it
const db = client.db("INDFLORIST");
const collection = db.collection("API");
return collection.insertOne({name: "Roger"});
}).then(function (result) {
console.log("Document inserted");
}).then(() => {
_client_.close(); // <-- close connection
}).catch(err => {
console.error(err);
});
您还可以通过所有
then
回调传递它const mongo = require("mongodb").MongoClient;
const config = require("./config.json");
mongo.connect(config.URI).then(client => {
const db = client.db("INDFLORIST");
const collection = db.collection("API");
return collection.insertOne({name: "Roger"}).then(() => client);
}).then(function (client) {
console.log("Document inserted");
return client;
}).then(client => {
client.close();
}).catch(err => {
console.error(err);
});
09-20 23:21