Skip to content

Instantly share code, notes, and snippets.

@sacgov
Created July 25, 2019 11:55
Show Gist options
  • Save sacgov/0d72d5b671ab6361b181d84744d25fc7 to your computer and use it in GitHub Desktop.
Save sacgov/0d72d5b671ab6361b181d84744d25fc7 to your computer and use it in GitHub Desktop.
Async in Babel
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
console.log(value)
value.then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this,
args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
console.log("next",value)
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
console.log("throw",err)
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function bar(ms, value) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(value), ms);
});
}
function foo() {
return _foo.apply(this, arguments);
}
function _foo() {
_foo = _asyncToGenerator(function*() {
let b = yield bar(500, "first");
console.log(b);
b = yield bar(2000, "second");
console.log(b);
});
return _foo.apply(this, arguments);
}
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment