我正在使用node和express为我的应用程序创建服务器。这是我的代码的样子:
async function _prepareDetails(activityId, dealId) {
var offerInfo;
var details = [];
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
const offers_collection = db.collection('collection_name');
await offers_collection.aggregate([
{ "$match": { 'id': Id} },
]).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
details = docs;
});
})
return details;
}
app.post('/getDetails',(request,response)=>{
var Id = request.body.Id;
var activityId = request.body.activityId;
_prepareDetails(activityId,Id).then(xx => console.log(xx));
response.send('xx');
})
在调用getDetails
API时我得到了
await is only valid in async function error (At line await offers_collection.aggregate)
在宣布async function
时,我也变红了下划线。我正在使用的节点版本是11.x.我也在使用firebase API。我在这做错了什么?
您缺少其中一个函数的异步声明。这是工作代码:
async function _prepareDetails(activityId, dealId) {
var offerInfo;
var details = [];
client.connect(async function(err) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
const offers_collection = db.collection('collection_name');
await offers_collection.aggregate([
{ "$match": { 'id': Id} },
]).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
details = docs;
});
})
return details;
}
app.post('/getDetails', async (request,response)=>{
var Id = request.body.Id;
var activityId = request.body.activityId;
let xx = await _prepareDetails(activityId,Id);
response.send('xx');
})
Await只能在异步函数中使用,因为await根据定义是异步的,因此必须使用回调或promise范例。通过将函数声明为异步,您告诉JavaScript将您的响应包装在promise中。您的问题出在以下行:
client.connect(function(err) {
这是我添加之前提到的异步的地方。
client.connect(async function(err) {
您会注意到我也使用了async,因为您以前会遇到问题。请注意原始代码中的两行:
_prepareDetails(activityId,Id).then(xx => console.log(xx));
response.send('xx');
您甚至在进行数据库调用之前都会发送响应,因为您没有在.then中包装response.send。你可以将response.send移动到.then,但是如果你要使用async / await,我会一直使用它。所以你的新路线看起来像:
app.post('/getDetails', async (request,response)=>{
var Id = request.body.Id;
var activityId = request.body.activityId;
let xx = await _prepareDetails(activityId,Id);
response.send('xx');
})