[英]NodeJS: How to await an asynchronous script called by runInNewContext?
I'm attempting to execute a custom Script object using runInNewContext .我正在尝试使用runInNewContext执行自定义Script对象。
let myScript = (async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
})();
let vm = new Script(myScript, myScriptOptions);
let result = vm.runInNewContext(mySandbox, myContextOptions);
console.log("Done running!");
However, the problem I'm running into is that I'd like runInNewContext
to actually wait until myScript
's asynchronous function is done running.但是,我runInNewContext
的问题是我希望runInNewContext
实际上等到myScript
的异步函数运行myScript
。 In other words, I would like "Done running!"换句话说,我想要“跑完了!” to be printed after the response has been fetched.在获取响应后打印。 Is this possible?这可能吗? How can I achieve it please?请问我该如何实现?
You must:你必须:
runInNewContext
.在调用runInNewContext
时等待该承诺。Therefore, let's say you want to return the user object:因此,假设您要返回用户对象:
let myScript = (async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
return user;
})();
Then, add await here然后,在这里添加等待
let result = await vm.runInNewContext(mySandbox, myContextOptions);
as if you try to print the value of result
it will be a promise so adding await will do what you are trying to achieve就像您尝试打印result
的值一样,这将是一个承诺,因此添加 await 将完成您想要实现的目标
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.