pas2js AsyncAWait: what changed
Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | 1 | # Overview | |
| 2 | 2 | ||
| 3 | 3 | [[pas2js|Pas2js]] supports the JS operators async/await to simplify the use of Promise, which itself simplifies writing asynchronous code, like starting a download, waiting for the result, then depending on the result start the next and so forth. Instead of writing a tedious and hard to read mass of sub functions an async procedure can be written in the common serial aka imperative way. | |
| 4 | 4 | ||
| 5 | 5 | # Basics | |
| 6 | 6 | ||
| 7 | 7 | First of we have the **async** keyword, which you add as a *procedure type modifier* to turn it into an *async function* (or *async procedure*). An *async function* knows how to expect the possibility of the *await* function being used to invoke **asynchronous** code. | |
| 8 | 8 | ||
| 9 | 9 | Usually you call an **async** function via the **await** function. To explain the inner workings it is useful to see what happens when you call an *async* function directly. Then you get a **TJSPromise**: | |
| 10 | 10 | ||
| 11 | 11 | ``` pascal | |
| 12 | 12 | uses JS; | |
| 13 | 13 | ||
| 14 | 14 | function Run: word; async; | |
| 15 | 15 | begin | |
| 16 | 16 | Result:=3; | |
| 17 | 17 | end; | |
| 18 | 18 | ||
| 19 | 19 | var p: TJSPromise; | |
| 20 | 20 | begin | |
| 21 | 21 | p:=Run(); // calling directly without await() returns a TJSPromise! | |
| 22 | 22 | end. | |
| 23 | 23 | ``` | |
| 24 | 24 | ||
| 25 | 25 | That's because an *async* function runs till an *await* and returns. If there is no *await* it works like a normal function, returning immediately a resolved TJSPromise. If it contains one or more *await* calls, each *await* pauses the execution of the async function and continues it asynchronously (single threaded) later. A *TJSPromise* has a hook for success and one for fail, which usually requires writing some anonymous functions. With async/await you can write much more readable code. | |
| 26 | 26 | ||
| 27 | 27 | # AWait | |
| 28 | 28 | ||
| 29 | 29 | Pas2js provides a built-in **await** function, which supports three flavours: | |
| 30 | 30 | ||
| 31 | 31 | ``` pascal | |
| 32 | 32 | function await(AsyncFunctionOfResultTypeT): T; | |
| 33 | 33 | function await(aType; p: TJSPromise): aType; // explicit promise requires the resolved type | |
| 34 | 34 | function await(aType; v: JSValue): aType; // explicit optional promise requires the resolved type | |
| 35 | 35 | ``` | |
| 36 | 36 | ||
| 37 | 37 | The **await** function can only be used inside a procedure with the **async** modifier. | |
| 38 | 38 | ||
| 39 | 39 | An **async** procedure can contain multiple **await** calls. | |
| 40 | 40 | ||
| 41 | 41 | Giving a promise to *await* works as if the following code is inside a *TJSPromise._then()*. If the promise is already resolved, *await* returns the value immediately. Otherwise the promise is returned as the *async* function result and the rest of the *async* function is executed when the promise is resolved. | |
| 42 | 42 | ||
| 43 | 43 | You can enclose an **await** function in *try..finally* or *try..except* for the case the *Promise* raises an exception. | |
| 44 | 44 | ||
| 45 | 45 | You can call *await* on a jsvalue, any promise will be resolved. For example when a JS function returns either a number or a promise of the number. | |
| 46 | 46 | ||
| 47 | 47 | You can define your own external class 'Promise'. It does not need to be called *TJSPromise*. | |
| 48 | 48 | ||
| 49 | 49 | ## Example Async try fetch | |
| 50 | 50 | ||
| 51 | 51 | Example demonstrating waiting for an async function, catching errors with a try..except and no anonymous functions. | |
| 52 | 52 | ||
| 53 | 53 | ``` pascal | |
| 54 | 54 | // Translated from https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await | |
| 55 | 55 | program tryfetch; | |
| 56 | 56 | ||
| 57 | 57 | {$mode objfpc} | |
| 58 | 58 | ||
| 59 | 59 | uses | |
| 60 | 60 | browserconsole, JS, Web, SysUtils; | |
| 61 | 61 | ||
| 62 | 62 | procedure myFetch; async; | |
| 63 | 63 | var | |
| 64 | 64 | response: TJSResponse; | |
| 65 | 65 | myBlob: TJSBlob; | |
| 66 | 66 | image: TJSHTMLImageElement; | |
| 67 | 67 | objectURL: string; | |
| 68 | 68 | begin | |
| 69 | 69 | try | |
| 70 | 70 | response := await(window.fetch('test1.png')); | |
| 71 | 71 | ||
| 72 | 72 | if not response.ok then | |
| 73 | 73 | raise Exception.Create('HTTP error! status: '+str(response.status)) | |
| 74 | 74 | else begin | |
| 75 | 75 | myBlob := await(response.blob()); | |
| 76 | 76 | objectURL := TJSURL.createObjectURL(myBlob); | |
| 77 | 77 | image := TJSHTMLImageElement(document.createElement('img')); | |
| 78 | 78 | image.src := objectURL; | |
| 79 | 79 | document.body.appendChild(image); | |
| 80 | 80 | end; | |
| 81 | 81 | except | |
| 82 | 82 | console.log(JSExceptValue); | |
| 83 | 83 | end; | |
| 84 | 84 | end; | |
| 85 | 85 | ||
| 86 | 86 | begin | |
| 87 | 87 | myFetch; | |
| 88 | 88 | end. | |
| 89 | 89 | ``` | |
| 90 | 90 | ||
| 91 | 91 | ## Example Manually created promise | |
| 92 | 92 | ||
| 93 | 93 | Example demonstrating using **await** with a non async function, creating the TJSPromise manually: | |
| 94 | 94 | ||
| 95 | 95 | ### Manually created promise Version 1 | |
| 96 | 96 | ||
| 97 | 97 | ``` pascal | |
| 98 | 98 | Program MyModule; | |
| 99 | 99 | ||
| 100 | 100 | uses JS, Web; | |
| 101 | 101 | ||
| 102 | 102 | function ResolveAfter2Seconds: TJSPromise; | |
| 103 | 103 | // returns immediately with a Promise, | |
| 104 | 104 | // which after 2 seconds gets resolved | |
| 105 | 105 | begin | |
| 106 | 106 | Result:=TJSPromise.new(procedure(resolve, reject : TJSPromiseResolver) | |
| 107 | 107 | begin | |
| 108 | 108 | window.setTimeout(procedure | |
| 109 | 109 | begin | |
| 110 | 110 | resolve('resolved'); | |
| 111 | 111 | end, | |
| 112 | 112 | 2000); // wait 2 seconds | |
| 113 | 113 | end); | |
| 114 | 114 | end; | |
| 115 | 115 | ||
| 116 | 116 | procedure AsyncCall; async; | |
| 117 | 117 | var s: string; | |
| 118 | 118 | begin | |
| 119 | 119 | writeln('calling'); | |
| 120 | 120 | s := await(string,resolveAfter2Seconds()); | |
| 121 | 121 | // the await pauses this procedure returning to the caller | |
| 122 | 122 | // when the Promise from resolveAfter2Seconds gets resolved | |
| 123 | 123 | // this procedure is continued | |
| 124 | 124 | writeln(s); // expected output: 'resolved' | |
| 125 | 125 | end; | |
| 126 | 126 | ||
| 127 | 127 | begin | |
| 128 | 128 | AsyncCall; | |
| 129 | 129 | // calling AsyncCall returns immediately, while the Promise is waiting | |
| 130 | 130 | writeln('called'); | |
| 131 | 131 | end. | |
| 132 | 132 | ``` | |
| 133 | 133 | ||
| 134 | 134 | Expected output: | |
| 135 | 135 | ||
| 136 | - | ||
| 137 | - | ||
| 138 | - | ||
| 136 | + | ```text | |
| 137 | + | calling | |
| 138 | + | called | |
| 139 | + | resolved | |
| 140 | + | ``` | |
| 139 | 141 | ||
| 140 | 142 | ### Manually created promise Version 2 | |
| 141 | 143 | ||
| 142 | 144 | Alternatively you can use the promise result type (here: string), by passing the *TJSPromise* to the **exit()** function: | |
| 143 | 145 | ||
| 144 | 146 | ``` pascal | |
| 145 | 147 | Program MyModule; | |
| 146 | 148 | ||
| 147 | 149 | uses JS, Web; | |
| 148 | 150 | ||
| 149 | 151 | function ResolveAfter2Seconds: string; async; | |
| 150 | 152 | // returns immediately with a Promise, | |
| 151 | 153 | // which after 2 seconds gets resolved | |
| 152 | 154 | var p: TJSPromise; | |
| 153 | 155 | begin | |
| 154 | 156 | p:=TJSPromise.new(procedure(resolve, reject : TJSPromiseResolver) | |
| 155 | 157 | begin | |
| 156 | 158 | window.setTimeout(procedure | |
| 157 | 159 | begin | |
| 158 | 160 | resolve('resolved'); | |
| 159 | 161 | end, | |
| 160 | 162 | 2000); // wait 2 seconds | |
| 161 | 163 | end); | |
| 162 | 164 | exit(p); // the exit() function takes either a TJSPromise or a string | |
| 163 | 165 | end; | |
| 164 | 166 | ||
| 165 | 167 | procedure AsyncCall; async; | |
| 166 | 168 | var s: string; | |
| 167 | 169 | begin | |
| 168 | 170 | writeln('calling'); | |
| 169 | 171 | s := await(resolveAfter2Seconds()); // no "string" needed | |
| 170 | 172 | // the await pauses this procedure returning to the caller | |
| 171 | 173 | // when the Promise from resolveAfter2Seconds gets resolved | |
| 172 | 174 | // this procedure is continued | |
| 173 | 175 | writeln(s); // expected output: 'resolved' | |
| 174 | 176 | end; | |
| 175 | 177 | ||
| 176 | 178 | begin | |
| 177 | 179 | AsyncCall; | |
| 178 | 180 | // calling AsyncCall returns immediately, while the Promise is waiting | |
| 179 | 181 | writeln('called'); | |
| 180 | 182 | end. | |
| 181 | 183 | ``` | |
| 182 | 184 | ||
| 183 | 185 | Note: The **Result** variable is of type string. You cannot assign it a promise. | |
| 184 | 186 | ||
| 185 | 187 | ## Example Multi await | |
| 186 | 188 | ||
| 187 | 189 | Example demonstrating starting multiple async functions and waiting for them while they execute in parallel. | |
| 188 | 190 | ||
| 189 | 191 | ``` pascal | |
| 190 | 192 | // Translated from https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await | |
| 191 | 193 | program tryfetchmany; | |
| 192 | 194 | ||
| 193 | 195 | {$mode objfpc} | |
| 194 | 196 | ||
| 195 | 197 | uses | |
| 196 | 198 | browserconsole, JS, Web, SysUtils, Types; | |
| 197 | 199 | ||
| 198 | 200 | function FetchBlob(url: string): TJSBlob; async; | |
| 199 | 201 | var | |
| 200 | 202 | response: TJSResponse; | |
| 201 | 203 | begin | |
| 202 | 204 | response := await(window.fetch(url)); | |
| 203 | 205 | if not response.ok then | |
| 204 | 206 | raise Exception.create('HTTP error! status: '+str(response.status)) | |
| 205 | 207 | else | |
| 206 | 208 | Result:=await(response.blob()); | |
| 207 | 209 | end; | |
| 208 | 210 | ||
| 209 | 211 | function FetchText(url: string): string; async; | |
| 210 | 212 | var | |
| 211 | 213 | response: TJSResponse; | |
| 212 | 214 | begin | |
| 213 | 215 | response := await(window.fetch(url)); | |
| 214 | 216 | if not response.ok then | |
| 215 | 217 | raise Exception.create('HTTP error! status: '+str(response.status)) | |
| 216 | 218 | else | |
| 217 | 219 | Result:=await(response.text()); | |
| 218 | 220 | end; | |
| 219 | 221 | ||
| 220 | 222 | procedure DisplayContent; async; | |
| 221 | 223 | var | |
| 222 | 224 | coffee, tea, description: TJSPromise; | |
| 223 | 225 | objectURL1, objectURL2, descText: String; | |
| 224 | 226 | values: TJSValueDynArray; | |
| 225 | 227 | image1, image2: TJSHTMLImageElement; | |
| 226 | 228 | para: TJSHTMLElement; | |
| 227 | 229 | begin | |
| 228 | 230 | try | |
| 229 | 231 | coffee := FetchBlob('test1.png'); | |
| 230 | 232 | tea := FetchBlob('test1.png'); | |
| 231 | 233 | description := FetchText('description.txt'); | |
| 232 | 234 | ||
| 233 | 235 | values := await(TJSValueDynArray,TJSPromise.all([coffee, tea, description])); | |
| 234 | 236 | ||
| 235 | 237 | objectURL1 := TJSURL.createObjectURL(values[0]); | |
| 236 | 238 | objectURL2 := TJSURL.createObjectURL(values[1]); | |
| 237 | 239 | descText := string(values[2]); | |
| 238 | 240 | ||
| 239 | 241 | image1 := TJSHTMLImageElement(document.createElement('img')); | |
| 240 | 242 | image2 := TJSHTMLImageElement(document.createElement('img')); | |
| 241 | 243 | image1.src := objectURL1; | |
| 242 | 244 | image2.src := objectURL2; | |
| 243 | 245 | document.body.appendChild(image1); | |
| 244 | 246 | document.body.appendChild(image2); | |
| 245 | 247 | ||
| 246 | 248 | para := TJSHTMLElement(document.createElement('p')); | |
| 247 | 249 | para.textContent := descText; | |
| 248 | 250 | document.body.appendChild(para); | |
| 249 | 251 | ||
| 250 | 252 | except | |
| 251 | 253 | writeln(JSExceptValue); | |
| 252 | 254 | end; | |
| 253 | 255 | end; | |
| 254 | 256 | ||
| 255 | 257 | begin | |
| 256 | 258 | DisplayContent; | |
| 257 | 259 | end. | |
| 258 | 260 | ``` | |
| 259 | 261 | ||
| 260 | 262 | # Navigation | |
| 261 | 263 | ||
| 262 | 264 | - [[pas2js|Pas2js]] | |
| 263 | 265 | ||
| 264 | 266 | --- | |
| 265 | 267 | *From the Free Pascal wiki, page "pas2js AsyncAWait", as it stood on 2020-12-31 after a change by Mattias2, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* | |
| 266 | 268 | Category: Pas2js |
