回调在 AWS lambda 调用中不起作用
callback not working in AWS lambda invoking
const connectToDB = async uri => {
if (cachedDb) {
return Promise.resolve(cachedDb);
}
return MongoClient.connect(config[STAGE].dbUrls[uri], { useNewUrlParser: true, useUnifiedTopology: true }).then(db => {
cachedDb = db;
return cachedDb;
});
};
exports.handler = (event, context, callback) => {
console.log("[Find All] [event] : ", event);
context.callbackWaitForEmptyEventLoop = false;
connectToDB('MONGODB_URI_FIND').then(database => {
let db = database.db(config[STAGE].dbUrls.DB_NAME);
console.log("db connection ", db);
fetchDataFromDb(db, event, callback);
});
};
const fetchDataFromDb = (db, event, callback) => {
const { table, query } = event;
const options = { ...query.options };
delete query.options;
const { sortFields, limit, skip } = options || {};
db.collection(table).find(query, options).sort(sortFields || {}).limit(limit || 999).skip(skip || 0).toArray((error, result) => {
console.log("Fetched data[] : ", { error, result });
if (error)
callback(null, { body: error });
else
callback(null, { body: result });
});
};
在上面的代码中,callback(null,{}) 函数没有执行,当我使用 return 或 context.done() 而不是 callback() 时代码正在运行。请帮我执行回调。
提前致谢
不得不用
context.callbackWaitsForEmptyEventLoop = false
改为
context.callbackWaitForEmptyEventLoop = false;
const connectToDB = async uri => {
if (cachedDb) {
return Promise.resolve(cachedDb);
}
return MongoClient.connect(config[STAGE].dbUrls[uri], { useNewUrlParser: true, useUnifiedTopology: true }).then(db => {
cachedDb = db;
return cachedDb;
});
};
exports.handler = (event, context, callback) => {
console.log("[Find All] [event] : ", event);
context.callbackWaitForEmptyEventLoop = false;
connectToDB('MONGODB_URI_FIND').then(database => {
let db = database.db(config[STAGE].dbUrls.DB_NAME);
console.log("db connection ", db);
fetchDataFromDb(db, event, callback);
});
};
const fetchDataFromDb = (db, event, callback) => {
const { table, query } = event;
const options = { ...query.options };
delete query.options;
const { sortFields, limit, skip } = options || {};
db.collection(table).find(query, options).sort(sortFields || {}).limit(limit || 999).skip(skip || 0).toArray((error, result) => {
console.log("Fetched data[] : ", { error, result });
if (error)
callback(null, { body: error });
else
callback(null, { body: result });
});
};
在上面的代码中,callback(null,{}) 函数没有执行,当我使用 return 或 context.done() 而不是 callback() 时代码正在运行。请帮我执行回调。 提前致谢
不得不用
context.callbackWaitsForEmptyEventLoop = false
改为
context.callbackWaitForEmptyEventLoop = false;