If you want to be able to await the eval you can use this:
await Object.getPrototypeOf(async function() {}).constructor("your code here")();
This uses the AsyncFunction constructor. MDN has a page on it which describes the differences between using it and using eval:
Note: async functions created with the AsyncFunction constructor do not create closures to their creation contexts; they are always created in the global scope.
When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the AsyncFunction constructor was called.
This is different from using eval with code for an async function expression.
This means that if you have variables that you want your evaled code to be able to access, you can either
- Pass them in as arguments:
const testVar = "Hello world";
const result = await Object.getPrototypeOf(async function() {}).constructor('testVar', `
console.log(testVar);
await myAsyncFunc();
return testVar;
`)(testVar);
// result will be "Hello world"
- Add them to
globalThis:
const testVar = "Hello world";
globalThis["testVar"] = testVar;
const result = await Object.getPrototypeOf(async function() {}).constructor(`
console.log(testVar);
await myAsyncFunc();
return testVar;
`)();
// result will be "Hello world"
delete globalThis["testVar"];
evalthe code? If you give us the real problem, perhaps it would turn out there is a different solutioneval-iffor example, or calling a whole different function, polymorphism, setting up lookup tables with functionality and so on.