MongoClient.connect的回调不调用
我尝试在aws lambda中调用回调,但是它不起作用,但是,如果我删除exports.lambdaHandler并仅由节点app.js调用它,它就可以正常工作。
exports.lambdaHandler = async (event, context) => {
try {
MongoClient.connect(url, {
useNewUrlParser: true
}, (err, client) => {
console.log("Connected successfully to server");
});
response = {
'statusCode': 200,
'body': JSON.stringify({
message: 'test'
})
}
return response
} catch (err) {
console.log(err);
return err;
}
};
应该返回
已成功连接到服务器
编辑
我将其更改为等待。现在很好
exports.lambdaHandler = async (event, context) => {
try {
const client = await MongoClient.connect(url, {
useNewUrlParser: true
})
const db = client.db(dbName)
await db.createCollection(collectionName)
client.close()
return {
'statusCode': 200,
'body': JSON.stringify({
message: 'test'
})
}
} catch (err) {
console.log(err);
return err;
}
};
答案 0 :(得分:0)
尝试此操作,它将返回结果,否则抛出一个错误,该错误将在下面捕获并由Lambda返回
exports.lambdaHandler = async (event, context) => {
try {
MongoClient.connect(url, {useNewUrlParser: true}, (err, client) => {
if (err) { console.log(err); throw(err); }
else {
console.log("Connected successfully to server");
console.log(client);
response = {
'statusCode': 200,
'body': JSON.stringify({message: client})
};
return response;
};
});
} catch (err) {
console.log(err);
return err;
}
};