首页 > 解决方案 > 如何在javascript中使用带有eval()函数的异步等待?

问题描述

我正在使用 eval 函数来评估字符串,并且我在 eval 函数上应用 await 以便获得所有值。但是等待不起作用

我的代码是这样的: -

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);
        });
    })
}

上述函数中使用的变量,它们的值:-

var value = { teamTwoId: 'wi', matchId: 'iccrzt20_2020_vg_g7', question: '哪支球队会赢得比赛?', functionName: 'matchWinnerTeam', options: { option2: 'West Indies', option1: 'Afghanistan' } , teamOneId: 'afg' }

在值 obj 中,函数名称:'matchWinnerTeam'。matchWinnerTeam() 是一个评估问题答案的函数。

变量键 = Q1

同样,我有 5 个类似的问题集。

问题陈述:-

我的 answerSet 对象值应该返回类似这样的值:- answerSet = { Q5: 'option2', Q3: 'option2', Q2: 'option2', Q4: 'option1', Q1: 'option2' } 但实际上它返回值每当我在我的节点 js 服务器上运行此函数时,都会出现类似的情况:-
{ Q5: 'option2', Q3: 'option2', }, { Q1: 'option2', Q4: 'option2', } ..... 和很快。

我发现的问题是 eval 函数必须等到它返回从 Q1 到 Q5 的所有值,但是 await 在 eval() 上不起作用。它评估两个问题的答案并返回这两个值,它不等待其余 3 个答案得到评估。

那么我可以像这样在 eval() 上使用 await 还是会有一些替代方法来执行此任务?

请帮忙。谢谢你

标签: javascriptnode.js

解决方案


好吧,我不认为使用 eval 是邪恶的,当然当你知道你在做什么的时候!据我了解,就您而言,您想等待 eval 完成。因此,您可以创建 promise 包装器并将 resolve 放入您的 eval 代码中,即像这样:

let toeval = `
  // Iteration number
  let i = 100;

  // Finish function
  const finish = () => {
    // Resolve
    resolve('This is data from eval');
  }

  // Delay function
  const delay = () => {
    setTimeout(() => {
      if(i) {
        i--;
        delay();
      } else finish();
    }, 10);
  }

  // Run delay
  delay();
`;

// Wait for eval wrapper
const waitEval = (ev) => {
  return new Promise((resolve, reject) => {
    eval(ev);
  });
};
                     
// Main function
(async () => {
  // Start message
  console.log(`Starting and waiting for eval to complete...`);
  
  // Run and wait for eval
  const x = await waitEval(toeval);
  console.log(`Result from eval: ${x}`);
  
  // Continue
  console.log(`Finished! Continue program...`);
})();

但请记住,如果您想以更安全的方式执行与上述相同的操作,请使用new Function代替eval

let toeval = `
  // Iteration number
  let i = 100;

  // Finish function
  const finish = () => {
    // Resolve
    resolve('This is data from eval');
  }

  // Delay function
  const delay = () => {
    setTimeout(() => {
      if(i) {
        i--;
        delay();
      } else finish();
    }, 10);
  }

  // Run delay
  delay();
`;

// Wait for new Function wrapper
const waitFn = (ev) => {
  return new Promise((resolve, reject) => {
    new Function('resolve', ev)(resolve);
  });
};
                     
// Main function
(async () => {
  // Start message
  console.log(`Starting and waiting for eval to complete...`);
  
  // Run and wait for eval
  const x = await waitFn(toeval);
  console.log(`Result from eval: ${x}`);
  
  // Continue
  console.log(`Finished!`);
})();


推荐阅读