async.md
This file
Path
docs/async.md
54 lines · 2.5 KiB · Markdown
Last changed by
Merge branch 'master' into v4Michel Weststratebefore adoption741e941
History of this fileTake it
Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 1–54why, one step back1---2id: async3title: Async producers & createDraft / finishDraft4sidebar_label: Async produce / createDraft5---67<div id="codefund"><!-- fallback content --></div>89<details>10 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 11: Creating _async_ producers (and why you shouldn’t)</summary>11 <br>12 <div style="padding:5px;">13 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t/embed" ></iframe>14 </div>15 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t">Hosted on egghead.io</a>16</details>1718It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:1920```javascript21import produce from "immer"2223const user = {24 name: "michel",25 todos: []26}2728const loadedUser = await produce(user, async function(draft) {29 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()30})31```3233_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._3435## `createDraft` and `finishDraft`3637`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:3839```javascript40import {createDraft, finishDraft} from "immer"4142const user = {43 name: "michel",44 todos: []45}4647const draft = createDraft(user)48draft.todos = await (await window.fetch("http://host/" + draft.name)).json()49const loadedUser = finishDraft(draft)50```5152Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.5354_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._