Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript / ES6, how do I wait for Python code to finish executing in a Jupyter Notebook?

My code calls a Jupyter Notebook routine (kernel.execute) which accepts a Python command and a callback function but this routine doesn't return a Promise.

Is it possible to asynchronously call kernel.execute in a loop and wait on each callback?

// 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");
}
like image 462
W. Bernbaum Avatar asked Jul 11 '26 09:07

W. Bernbaum


1 Answers

You can use es6 async, await for that:

// 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>
like image 142
Peter Avatar answered Jul 13 '26 22:07

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!