Skip to content

Commit

Permalink
Merge pull request #1379 from sveltejs/gh-1251
Browse files Browse the repository at this point in the history
preserve outer context for await blocks
  • Loading branch information
Rich-Harris authored Apr 29, 2018
2 parents ed605bf + 5fd4965 commit d8ca0e3
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/compile/nodes/AwaitBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ export default class AwaitBlock extends Node {
block.addVariable(promise);
block.addVariable(resolved);

block.maintainContext = true;

// the `#component.root.set({})` below is just a cheap way to flush
// any oncreate handlers. We could have a dedicated `flush()` method
// but it's probably not worth it
Expand All @@ -119,21 +121,19 @@ export default class AwaitBlock extends Node {
}
}
function ${handle_promise}(${promise}, ctx) {
function ${handle_promise}(${promise}) {
var ${token} = ${await_token} = {};
if (@isPromise(${promise})) {
${promise}.then(function(${value}) {
${this.value ? deindent`
var ctx = #component.get();
${resolved} = { ${this.value}: ${value} };
${replace_await_block}(${token}, ${create_then_block}, @assign(@assign({}, ctx), ${resolved}));
` : deindent`
${replace_await_block}(${token}, null, null);
`}
}, function (${error}) {
${this.error ? deindent`
var ctx = #component.get();
${resolved} = { ${this.error}: ${error} };
${replace_await_block}(${token}, ${create_catch_block}, @assign(@assign({}, ctx), ${resolved}));
` : deindent`
Expand All @@ -155,7 +155,7 @@ export default class AwaitBlock extends Node {
}
}
${handle_promise}(${promise} = ${snippet}, ctx);
${handle_promise}(${promise} = ${snippet});
`);

block.builders.create.addBlock(deindent`
Expand Down
31 changes: 31 additions & 0 deletions test/runtime/samples/await-in-each/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
let fulfil;

let thePromise = new Promise(f => {
fulfil = f;
});

const items = [{
title: 'a title',
data: thePromise
}];

export default {
data: {
items
},

html: `
<p>a title: loading...</p>
`,

test(assert, component, target) {
fulfil(42);

return thePromise
.then(() => {
assert.htmlEqual(target.innerHTML, `
<p>a title: 42</p>
`);
});
}
};
7 changes: 7 additions & 0 deletions test/runtime/samples/await-in-each/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{#each items as item}
{#await item.data}
<p>{item.title}: loading...</p>
{:then result}
<p>{item.title}: {result}</p>
{/await}
{/each}

0 comments on commit d8ca0e3

Please sign in to comment.