Skip to content
Myr

async.md

This file

Path

docs/async.md

45 lines · 1.9 KiB · Markdown

Last changed by

Docs websiteMichel Weststratebefore adoption6d903d1

History of this file

Take it

Docs WIPMichel Weststratebefore adoption12298be

lines 1–3why, one step back
1---
2id: async3title: Async producers & createDraft / finishDraft

Docs websiteMichel Weststratebefore adoption6d903d1

line 4why, one step back
4sidebar_label: Async produce / createDraft

Docs WIPMichel Weststratebefore adoption12298be

lines 5–45why, one step back
5---
67<div id="codefund"><!-- fallback content --></div>89It 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:1011```javascript12import produce from "immer"1314const user = {15 name: "michel",16 todos: []17}1819const loadedUser = await produce(user, async function(draft) {20 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()21})22```2324_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._2526## `createDraft` and `finishDraft`2728`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:2930```javascript31import {createDraft, finishDraft} from "immer"3233const user = {34 name: "michel",35 todos: []36}3738const draft = createDraft(user)39draft.todos = await (await window.fetch("http://host/" + draft.name)).json()40const loadedUser = finishDraft(draft)41```4243Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.4445_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._