Skip to content

Commit

Permalink
Merge pull request #3442 from sveltejs/gh-2443
Browse files Browse the repository at this point in the history
set context in await blocks
  • Loading branch information
Rich-Harris committed Aug 22, 2019
2 parents 860040a + 0f65b6c commit 415dc5f
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/runtime/internal/await_block.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { assign, is_promise } from './utils';
import { check_outros, group_outros, transition_in, transition_out } from './transitions';
import { flush } from './scheduler';
import { get_current_component, set_current_component } from './lifecycle';

export function handle_promise(promise, info) {
const token = info.token = {};
Expand Down Expand Up @@ -40,10 +41,15 @@ export function handle_promise(promise, info) {
}

if (is_promise(promise)) {
const current_component = get_current_component();
promise.then(value => {
set_current_component(current_component);
update(info.then, 1, info.value, value);
set_current_component(null);
}, error => {
set_current_component(current_component);
update(info.catch, 2, info.error, error);
set_current_component(null);
});

// if we previously had a then/catch block, destroy it
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/internal/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function set_current_component(component) {
current_component = component;
}

function get_current_component() {
export function get_current_component() {
if (!current_component) throw new Error(`Function called outside component initialization`);
return current_component;
}
Expand Down
6 changes: 6 additions & 0 deletions test/runtime/samples/context-in-await/Child.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
import { getContext } from 'svelte';
const num = getContext('test');
</script>

<p>Context value: {num}</p>
13 changes: 13 additions & 0 deletions test/runtime/samples/context-in-await/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export default {
html: `
<p>...waiting</p>
`,

async test({ assert, component, target }) {
await component.promise;

assert.htmlEqual(target.innerHTML, `
<p>Context value: 123</p>
`);
}
};
14 changes: 14 additions & 0 deletions test/runtime/samples/context-in-await/main.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script>
import { setContext } from 'svelte';
import Child from './Child.svelte';
setContext('test', 123);
export let promise = Promise.resolve();
</script>

{#await promise}
<p>...waiting</p>
{:then}
<Child />
{/await}

0 comments on commit 415dc5f

Please sign in to comment.