gpt4 book ai didi

javascript - 在 Javascript/ES6 中,如何等待 Python 代码在 Jupyter Notebook 中完成执行?

转载 作者:行者123 更新时间:2023-11-29 23:27:51 24 4
gpt4 key购买 nike

我的代码调用 Jupyter Notebook 例程 (kernel.execute),它接受 Python 命令和回调函数,但该例程不返回 Promise。

是否可以在循环中异步调用 kernel.execute 并等待每个回调?

// these functions print timestamps to the console
var function_1 = {
iopub: {
output: parse_json_from_python_and_stash_something_in_object_1();
}
}

var function_n = {
iopub: {
output: parse_json_from_python_and_stash_something_in_object_n();
}
}

var objects_to_populate = {
object_1: function_1,
object_n: function_n
}

handler.on('click', function() {

$.each(objects_to_populate, function(obj, cb) {
let arg = '\'' + "Hello from Javascript" + '\'';
let command = `print(${arg})`;

// Jupyter Notebook function; calls Python (slow)
kernel.execute(command, cb);
}

ugly_sleep_hack();
// Do something here after every object has been populated

print_timestamp_to_console("Finished");
}

最佳答案

你可以使用 es6 async, await:

// emulating async function here
let kernel = {
execute: (ignore, cb) => setTimeout(cb, 2000)
}

let objects_to_populate = {
1: () => console.log(1),
2: () => console.log(2),
3: () => console.log(3)
};

let execute = function(command, cb) {
return new Promise(function(resolve, reject) {
kernel.execute(command, function() {
cb();
resolve();
});
})
};

let handler = $('#testBtn');

handler.on('click', async function() {
let executes = [];


$.each(objects_to_populate, function(obj, cb) {

let arg = '\'' + "Hello from Javascript" + '\'';
let command = `print(${arg})`;

// Jupyter Notebook function; calls Python (slow)
executes.push(execute(command, cb));
});

await Promise.all(executes);
console.log('Something');
// Do something here after every object has been populated
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testBtn">Test</button>

关于javascript - 在 Javascript/ES6 中,如何等待 Python 代码在 Jupyter Notebook 中完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409285/

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