Lambda nodeJS 4.3未完成/执行成功回调 [英] Lambda nodeJS 4.3 not finishing/executing success callback
本文介绍了Lambda nodeJS 4.3未完成/执行成功回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
callback(null)
不起作用。甚至尝试将它包装在一个try catch块中,但没有得到任何东西。 以下是完整的函数:
var Firebase = require('firebase');
var request = require('request');
// noinspection AnonymousFunctionJS
/ **
*
* @param event - 从Lambda
* @param context - 从Lambda
* @param回调 - 从Lambda
* /
exports.handler = function(event,context,callback){
var AUTOPILOT_API_KEY = getKey(event.stage,'AUTOPILOT_API_KEY');
var AUTOPILOT_JOURNEY_ID = getKey(event.stage,'AUTOPILOT_JOURNEY_ID');
activate();
function activate(){
console.log('event:',event);
if(validPayload(event,context)){
addDefaultPresets(event.uid);
addToAutopilot(event.user,event.uid);
$ b $ **
*检查是否已收到必要的有效负载
*如果是:返回true并允许进程继续
*如果NO:抛出context.fail与有用的错误信息
*在
* http代码+ 3数字的自定义错误代码命名约定下操作ULM错误代码
* @ param事件 - 从Lambda
* @param context - 从Lambda
* @returns {boolean} - 有效载荷是否包含所需数据
* /
函数validPayload(event,context ){
返回true; //删除BREVITY
$ b $ **
*将用户作为联系人添加到自动驾驶仪,并将他们
*添加到触发ID为0001
* @param {Object} user
* @param {string} uid由Firebase生成为注册用户的唯一标识符
* /
功能addToAutopilot(user,uid){
//删除BREVITY
request({
method:'POST',
url:'https://api2.autopilothq.com/v1 / trigger /'+ AUTOPILOT_JOURNEY_ID +'/ contact',
headers:{$ b $'autopilotapikey':AUTOPILOT_API_KEY,
'Content-Type':'application / json'
},
body:JSON.stringify(payload)
},function(error,response,body){
// noinspection MagicNumberJS
if(response.statusCode!== 200){
errorResponse.status = response.sta tusCode;
errorResponse.error = {
errorMessage:error,
user:event.user,
response:response,
body:body
};
console.log('应该抛出错误回调');
context.fail(JSON.stringify(errorResponse));
} else {
console.log('should throw SUCCESS callback');
console.log(JSON.stringify({
status:response.statusCode,
message:User successfully added to Autopilot account& journey
}));
callback(null);
}
console.log('Finished addToAutopilot()');
});
}
$ b / **
*添加一组预设的新用户帐号
* @param uid {String} - Firebase UID
* /
函数addDefaultPresets(uid){
//为BREVITY编辑
var presets = ref.child('users')。child(uid).child('预置);
console.log('Starting addDefaultPresets()');
activate();
function activate(){
console.info('activating ...');
//为每个字段
fields.forEach(function(field){
//遍历每个预设
presetData [field] .forEach(function(label){
//并通过addDefaultPreset()添加到firebase数据库中,如果唯一
presetIsUnique(field,label);
})
});
console.log('Finished addDefaultPresets()');
$ b函数presetIsUnique(field,label){
presets.child(field).orderByChild('label')
.equalTo(label)
.once('value',function(snapshot){
var val = snapshot.val();
if(!val){
addDefaultPreset(field,label);
} else {
console.error('already exists',field,label);
}
});
函数addDefaultPreset(field,label){
// noinspection MagicNumberJS
presets.child(field).push()。set({
创建者:'default',
dateAdded:Math.floor(Date.now()/ 1000),
label:label
,setCallback);
函数setCallback(err){
if(err){
console.error(err);
} else {
console.info('added preset');
$ b函数getKey(stage,keyId){
var keys = {
AUTOPILOT_API_KEY:{
staging:'dev123',
prod:'prod123'
},
AUTOPILOT_JOURNEY_ID:{
staging:'XXX',
产品:'XXXX'
},
FIREBASE_URL:{
staging:'https://staging.firebaseio.com/',
prod:'https://prod.firebaseio.com/'
}
};
if(stage ==='prod'){
return key [keyId] [stage];
} else {
return key [keyId] ['staging'];
}
}
};
解决方案
。默认情况下,lambda在终止之前一直等到事件循环为空。您可以设置 context.callbackWaitsForEmptyEventLoop = false
告诉lambda在调用回调后立即终止函数,即使事件循环中还有项目。
Despite running the log statement immediately above it, my call to callback(null)
isn't working. Even tried wrapping it in a try catch block but got nothing.
For reference, here's the full function:
var Firebase = require('firebase');
var request = require('request');
//noinspection AnonymousFunctionJS
/**
*
* @param event - from Lambda
* @param context - from Lambda
* @param callback - from Lambda
*/
exports.handler = function (event, context, callback) {
var AUTOPILOT_API_KEY = getKey(event.stage, 'AUTOPILOT_API_KEY');
var AUTOPILOT_JOURNEY_ID = getKey(event.stage, 'AUTOPILOT_JOURNEY_ID');
activate();
function activate () {
console.log('event:', event);
if (validPayload(event, context)) {
addDefaultPresets(event.uid);
addToAutopilot(event.user, event.uid);
}
}
/**
* checks that the necessary payload has been received
* if YES: returns true and allows process to continue
* if NO: throws context.fail with useful error message(s)
* operating under custom error code naming convention of
* http code + 3 digit ULM error code
* @param event - from Lambda
* @param context - from Lambda
* @returns {boolean} - whether the payload contains the required data
*/
function validPayload (event, context) {
return true; // REDACTED FOR BREVITY
}
/**
* Adds the user to Autopilot as a contact and adds them
* to the journey with trigger id 0001
* @param {Object} user
* @param {string} uid generate by Firebase as unique identifier of registered user
*/
function addToAutopilot (user, uid) {
// REDACTED FOR BREVITY
request({
method: 'POST',
url: 'https://api2.autopilothq.com/v1/trigger/' + AUTOPILOT_JOURNEY_ID + '/contact',
headers: {
'autopilotapikey': AUTOPILOT_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
}, function (error, response, body) {
//noinspection MagicNumberJS
if (response.statusCode !== 200) {
errorResponse.status = response.statusCode;
errorResponse.error = {
errorMessage: error,
user: event.user,
response: response,
body: body
};
console.log('should throw ERROR callback');
context.fail(JSON.stringify(errorResponse));
} else {
console.log('should throw SUCCESS callback');
console.log(JSON.stringify({
status: response.statusCode,
message: "User successfully added to Autopilot account & journey"
}));
callback(null);
}
console.log('Finished addToAutopilot()');
});
}
/**
* Adds a collection of presets the the account of the new user
* @param uid {String} - Firebase UID
*/
function addDefaultPresets (uid) {
// REDACTED FOR BREVITY
var presets = ref.child('users').child(uid).child('presets');
console.log('Starting addDefaultPresets()');
activate();
function activate () {
console.info('activating...');
// for each field
fields.forEach(function (field) {
// iterate over each preset
presetData[field].forEach(function (label) {
// and add to firebase db via addDefaultPreset() if unique
presetIsUnique(field, label);
})
});
console.log('Finished addDefaultPresets()');
}
function presetIsUnique (field, label) {
presets.child(field).orderByChild('label')
.equalTo(label)
.once('value', function (snapshot) {
var val = snapshot.val();
if (!val) {
addDefaultPreset(field, label);
} else {
console.error('already exists', field, label);
}
});
}
function addDefaultPreset (field, label) {
//noinspection MagicNumberJS
presets.child(field).push().set({
creator: 'default',
dateAdded: Math.floor(Date.now() / 1000),
label: label
}, setCallback);
}
function setCallback (err) {
if (err) {
console.error(err);
} else {
console.info('added preset');
}
}
}
function getKey (stage, keyId) {
var keys = {
AUTOPILOT_API_KEY: {
staging: 'dev123',
prod: 'prod123'
},
AUTOPILOT_JOURNEY_ID: {
staging: 'XXX',
product: 'XXXX'
},
FIREBASE_URL: {
staging: 'https://staging.firebaseio.com/',
prod: 'https://prod.firebaseio.com/'
}
};
if (stage === 'prod') {
return keys[keyId][stage];
} else {
return keys[keyId]['staging'];
}
}
};
解决方案
It seems like firebase is keeping something in the event loop. By default, lambda waits until the event loop is empty before terminating. You can set context.callbackWaitsForEmptyEventLoop = false
to tell lambda to terminate the function soon after the callback is called, even if there is still items in the event loop.
这篇关于Lambda nodeJS 4.3未完成/执行成功回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文