我有一个节点函数,该函数调用mongo来请求一些数据。没有错误,但似乎也未连接到mongo并获取数据。有什么我做不对的事情吗?
const MongoClient = require('mongodb').MongoClient;
module.exports = async (context, req) => {
try {
let connectionString = 'mongodb://<username>:<password>@<endpoint>.documents.azure.com:10255/?ssl=true';
context.log('******************** 11 *************************');
MongoClient.connect(connectionString, {uri_decode_auth: true}, function(err, client) {
if (err) {
context.log('Failed to connect');
context.res = { status: 500, body: err.message }
return context.done();
}
context.log('******************** 22 *************************');
client.db("stuff").collection("items").find({}).toArray(function(err, result) {
if (err) {
context.log('Error running query');
context.res = { status: 500, body: err.message }
return context.done();
}
context.log(result);
context.log('******************** 44 *************************');
let message = "Hello " + req.query.name + ". Have a nice day!. Really...";
context.res = {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: {"message": message}
};
context.done();
client.close();
});
});
}
catch(error) {
context.log('caught the error');
context.log(error)
}
};
我在天蓝色日志中看到的输出是:
2018-10-26T12:38:07 Welcome, you are now connected to log-streaming service.
2018-10-26T12:38:17.218 [Information] Executing 'Functions.zap-search' (Reason='This function was programmatically called via the host APIs.',
Id=e294fde0-d249-4237-a421-e85bde40f843)
2018-10-26T12:38:17.715 [Information] ******************** 11 *************************
2018-10-26T12:38:18.461 [Information] Executed 'Functions.zap-search' (Succeeded, Id=e294fde0-d249-4237-a421-e85bde40f843)
答案 0 :(得分:3)
在使用V2的Azure函数时,您需要确定是否要使用承诺或回调。您发布的代码基于回调,但是由于使用了async
关键字而被作为承诺导出,并且由于未等待MongoClient.connect,因此运行时在执行这些结果之前会退出您的函数。
如果您删除了async
关键字,应该会开始看到所需的结果。