Reputation: 80
I've recently been working on Alexa inside of Lamda using node.js. I had to implement promises to make sure that requests happened in the correct order and waited for DB queries to finish. I do have that working, but now I am unable to execute any "this.emit" statements from within the promise, probably due to the promise structure using "this" for its own purposes.
Any assistance would be appreciated! This is very similar to the following thread: AWS Lambda Node.js execute this.emit after async HTTP request completes
I would have commented there, but don't have the rep, DOH! Anyway here is the code. The emit statements are near the bottom. Thanks in advance!
'LaunchRequest': function() {
var accessToken = this.event.session.user.accessToken;
// Check for User Data in Session Attributes
if (accessToken) {
// Get User Details from Login with Amazon
AmazonAPI('https://api.amazon.com/user/profile?access_token=', accessToken, 'GET')
.then(function(userDetails) {
console.log(userDetails);
return (userDetails);
})
.then(function(userDetails) {
console.log('STEP 2: Starting DB Lookup');
var email = userDetails.email;
return userCheck(email);
})
.then(function(userDetails) {
var noAccount = '{"Items":[],"Count":0,"ScannedCount":0}';
var existString = JSON.stringify(userDetails);
var activeState = existString.includes("ACTIVE");
var linkState = existString.includes("linkComplete");
console.log(linkState);
var truth = true;
if (existString == noAccount) {
return AmazonAPITwo('https://api.amazon.com/user/profile?access_token=', accessToken, 'GET')
.then(function(userDetails) {
console.log(userDetails);
var name = userDetails.name;
var email = userDetails.email;
var postal_code = userDetails.postal_code;
var amazonId = userDetails.user_id;
var currentState = userDetails.state;
var state = "linkComplete";
return userCreate(accessToken, email, name, amazonId, postal_code, state);
})
.then(function() {
console.log('Staring PhaseOne Questions');
this.emit('phaseOne');
});
} else if (activeState == truth) {
console.log('Saying Fact');
this.emit('giveFactIntent');
} else if (linkState == truth) {
console.log('Staring PhaseOne Questions');
this.emit('phaseOne');
}
})
.catch(function(err) {
console.log('Caught Error:', err);
});
} else {
// Account Not Linked
this.emit(':tellWithLinkAccountCard', 'Welcome! ');
}
},
Upvotes: 1
Views: 359
Reputation: 10204
Keep a reference on this to use later :
const that = this; // at the top
// later on in nested function
that.emit();
Upvotes: 1