n-riesco / jp-babel

jp-babel is a babel kernel for the Jupyter notebook
Other
86 stars 16 forks source link

Async / Await #17

Closed jmatsushita closed 7 years ago

jmatsushita commented 7 years ago

Hi there,

It would be nice to be able to use the new async/await syntax. Could it be as simple as wrapping the REPL as mentioned here? https://github.com/tc39/ecmascript-asyncawait/issues/9#issuecomment-39000615

Cheers,

Jun

jmatsushita commented 7 years ago

This idea is that would allow doing something like this:

let fetch = require('isomorphic-fetch');
var $$html$$ = await fetch('http://google.com');
n-riesco commented 7 years ago

Since this feature has to be implemented in the [NEL]() package, I've opened an issue there. See https://github.com/n-riesco/nel/issues/6 .


In the meantime, as a workaround, you could define a helper function like this (untested):

function awaitFor(promise, send, $_) {
    send = send || $$.sendResult;
    $_ = $_ || $$;

    $_.async();

    promise.then(function(result) {
        send.call($_, result);
    }).catch(function(error) {
        $_.sendError(error);
    });
}

so that your example would be re-written as:

const fetch = require('isomorphic-fetch');
awaitFor(fetch('http://google.com'), $$.html);

And another example:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);

awaitFor(readdir('.'));