How could we use the javascript await
operator in the browser using a external javascript library?
For example, if we have the following html code:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='awesome.lib.js'></script>
<script type='text/javascript'>
async function slow() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("slow finished");
resolve();
}, 3000);
});
}
function fast() {
console.log("fast");
}
async function run() {
await slow();
fast();
}
run();
</script>
</head>
<body>
</body>
</html>
which libraries can we use (where awesome.lib.js
are these libraries) to bring the await operator to the browser?
How can we code a working example?
I know that we can transpile the code, but I'm searching for a clever solution that we can just add a third party library and voilá, it works!
If we are using the Google Traceur Transpiler we can transpile the code (http://jsfiddle.net/msfrisbie/yk6r7gxr/) and get a code that looks like the one below. But the problem is that we need transpile the code first.
Another thing is I would like to avoid using some things that is not javascript like <script type='text/whatevernotjavascript'>...code...code</script>
.
How can we do this? This would be very awesome, util and savior.
<script type="text/javscript">
$traceurRuntime.ModuleStore.getAnonymousModule(function(require) {
"use strict";
var $__1 = $traceurRuntime.initTailRecursiveFunction(slow),
$__3 = $traceurRuntime.initTailRecursiveFunction(run);
function slow() {
return $traceurRuntime.call(function() {
return $traceurRuntime.continuation($traceurRuntime.asyncWrap, $traceurRuntime, [$traceurRuntime.initTailRecursiveFunction(function($ctx) {
return $traceurRuntime.call(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$ctx.returnValue = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("slow finished");
resolve();
}, 3000);
});
$ctx.state = 2;
break;
case 2:
$ctx.state = -2;
break;
default:
return $traceurRuntime.continuation($ctx.end, $ctx, []);
}
}, this, arguments);
}), this]);
}, this, arguments);
}
function fast() {
console.log("fast");
}
function run() {
return $traceurRuntime.call(function() {
return $traceurRuntime.continuation($traceurRuntime.asyncWrap, $traceurRuntime, [$traceurRuntime.initTailRecursiveFunction(function($ctx) {
return $traceurRuntime.call(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
Promise.resolve(slow()).then($ctx.createCallback(2), $ctx.errback);
return;
case 2:
fast();
$ctx.state = -2;
break;
default:
return $traceurRuntime.continuation($ctx.end, $ctx, []);
}
}, this, arguments);
}), this]);
}, this, arguments);
}
run();
return {};
});
//# sourceURL=traceured.js