I am using eval function to evaluate the strings and I am applying await on eval function so that I will get all the values. But the await is not working
My code is something like this:-
if (matchCard.card.status != "notstarted") {
return new Promise((resolve) => {
questionSetObj.forEach(async ([key, value], index) => {
let thisVal = await eval(value.functionName)(value, key);
console.log("thisVal....", thisVal)
if (thisVal) {
if (thisVal[key] != "NotFound") answerSet[key] = thisVal[key]
}
console.log("answerSet", answerSet);
answerSetArray.push(answerSet);
if (index === questionSetObj.length - 1) resolve(answerSetArray);
});
})
}
Variables used in the above functions, their values:-
var value = { teamTwoId: 'wi', matchId: 'iccrzt20_2020_vg_g7', question: 'Which team will win the match?', functionName: 'matchWinnerTeam', options: { option2: 'West Indies', option1: 'Afghanistan' }, teamOneId: 'afg' }
In value obj, functionName: 'matchWinnerTeam'. matchWinnerTeam() is a function to evaluate the answer of the question.
var key = Q1
Similarly, I have 5 questions sets similarly like this.
Problem Statement:-
My answerSet object value should return values something like this:-
answerSet = {
Q5: 'option2',
Q3: 'option2',
Q2: 'option2',
Q4: 'option1',
Q1: 'option2'
}
But actually it returns values something like this whenever I run this function on my node js server:-
{
Q5: 'option2',
Q3: 'option2',
}, {
Q1: 'option2',
Q4: 'option2',
} ..... and so on.
Issue what I found is that eval function has to wait until it returns all the values from Q1 to Q5 but await is not working on eval(). It evaluates answers of two questions and it returns those two values, it is not waiting for rest 3 answers to get evaluated.
So can I use await on eval() like this or there will be some alternate method to perform this task?
Please Help. Thank You
eval. You only use it to fetch a function by name - you can instead pass have an object where you get the function by name or better yet,questionSetObjcan directly use the functions, so you don't need toevalthem but execute them[{f: function() { console.log("one"); } }, {f: function() { console.log("two") } }]instead of[{functionName: "functionOne" }, { ffunctionName: "functionTwp" }].