gpt4 book ai didi

node.js - NodeJS : How to await an asynchronous script called by runInNewContext?

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:40 26 4
gpt4 key购买 nike

我正在尝试执行自定义 Script对象使用 runInNewContext .

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!");

但是,我遇到的问题是我希望 runInNewContext 实际上等待 myScript 的异步函数完成运行。换句话说,我想要“跑完!”获取响应后打印。 这可能吗?请问我怎样才能实现它?

最佳答案

您必须:

  1. 让您的原始函数返回一个 promise
  2. 调用 runInNewContext 时等待该 promise 。

因此,假设您要返回用户对象:

let myScript = (async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
return user;
})();

然后,在这里添加await

let result = await vm.runInNewContext(mySandbox, myContextOptions);

就好像您尝试打印结果的值一样,这将是一个 promise 所以添加等待将实现您想要实现的目标

关于node.js - NodeJS : How to await an asynchronous script called by runInNewContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59817554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com