It's a Stack Snippets bugUpdate: This is fixed as of Oct 3 2024, see the updates in this bug report (butwhich SE won't call it a bug, they call itcalled a "feature request"), please see this question.
The problem is that the version of babel-standalone used by Stack Snippets is (well) out of date and doesn't understand async
/await
. Amusingly, on any modern browser, if you untick the Babel box in the snippet, it'll work. But if you want JSX compilation, you need to tick the box, so using async
in (say) a React question won't work.
It also works if you use a current version of babel-standalone, like this:
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script type="text/babel">
function bar() {
return new Promise((resolve,reject) => {
setTimeout(()=> {
resolve('resolved after 1500ms');
},1500);
// return resolve('resolved');
});
}
async function foo() {
const result = await bar();
console.log(result);
}
foo();
</script>
Note that you can't put the code that Babel will process in the JavaScript panel in the snippet editor. You have to put it in the HTML panel instead, in a <script type="text/babel">...</script>
tag.