Skip to content

Instantly share code, notes, and snippets.

@syang
Created June 5, 2017 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syang/d7ff47b216919fcce93ffb47f278b35f to your computer and use it in GitHub Desktop.
Save syang/d7ff47b216919fcce93ffb47f278b35f to your computer and use it in GitHub Desktop.
Can we avoid this two level callback hell?
exports.getQuestionDetails = (event, context, callback) => {
var keys = event.pathParameters.questionId.split("-");
console.log("keys: ", keys);
var result = {};
// Let first query the question table and retrive the question
let params = {
TableName: tableName,
Key: {
category: keys[0],
ts: keys[1]
}
};
let dbGet = (params, result) => {
return dynamo.get(params).promise()
};
dbGet(params, result).then((data) => {
if (!data.Item) {
callback(null, createResponseWithHeader(404, "ITEM NOT FOUND"));
return;
}
result.question = JSON.parse(JSON.stringify(data.Item.question));
console.log("result.question: ", result.question);
// callback(null, createResponseWithHeader(200, JSON.stringify(data.Item.question)));
}).catch((err) => {
console.log(`GET ITEM FAILED FOR doc = ${params.Key.id}, WITH ERROR: ${err}`);
callback(null, createResponseWithHeader(500, err));
});
// Let then query the answer table and retrive the list of answers (or empty)
params = {
TableName : answerTableName,
KeyConditionExpression: "#yr = :yyyy",
ExpressionAttributeNames:{
"#yr": "qid"
},
ExpressionAttributeValues: {
":yyyy":event.pathParameters.questionId
}
};
let dbQuery = (params, result) => {
// return dynamo.get(params).promise()
return dynamo.query(params).promise()
};
dbQuery(params, result).then((data) => {
// console.log(data);
if (!data.Items) {
// callback(null, createResponseWithHeader(404, "ITEM NOT FOUND"));
return;
}
result = JSON.parse(JSON.stringify(data.Items));
console.log("result: ", result);
// callback(null, createResponseWithHeader(200, JSON.stringify(data.Items)));
}).catch((err) => {
console.log(`GET ITEM FAILED FOR doc, WITH ERROR: ${err}`);
callback(null, createResponseWithHeader(500, err));
});
console.log("result: ", result);
callback(null, createResponseWithHeader(200, JSON.stringify(result)));
};
@syang
Copy link
Author

syang commented Jun 5, 2017

The intent was this:

  1. first query table "question" (see code from line 6), and if there exist result (i.e., there exist a record in table "question" corresponding the question id) we do next

  2. query table "answers" (see code from line 32)

But because of callback is async (see line 61 and 63), result object is still {} although there are record from step 1 and step 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment