Created
June 5, 2017 17:40
-
-
Save syang/d7ff47b216919fcce93ffb47f278b35f to your computer and use it in GitHub Desktop.
Can we avoid this two level callback hell?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The intent was this:
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
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