From 6d62bcd2679360f8b364fe96875cf60089902c02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20Codo=C3=B1er?= Date: Mon, 7 Oct 2024 16:56:35 +0200 Subject: [PATCH] document meteor methods callAsync promises --- v3-docs/docs/api/meteor.md | 66 +++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/v3-docs/docs/api/meteor.md b/v3-docs/docs/api/meteor.md index 6d68cec3a2..5f3899014a 100644 --- a/v3-docs/docs/api/meteor.md +++ b/v3-docs/docs/api/meteor.md @@ -401,7 +401,71 @@ Use `Meteor.call` only to call methods that do not have a stub, or have a sync s -`Meteor.callAsync` is just like `Meteor.call`, except that it'll return a promise that you need to solve to get the result. +`Meteor.callAsync` is just like `Meteor.call`, except that it'll return a promise that you need to solve to get the server result. Along with the promise returned by `callAsync`, you can also handle `stubPromise` and `serverPromise` for managing client-side simulation and server response. + +The following sections guide you in understanding these promises and how to manage them effectively. + +#### serverPromise + +```javascript +try { + await Meteor.callAsync('greetUser', 'John'); + // ๐ŸŸข Server ended with success +} catch(e) { + console.error("Error:", error.reason); // ๐Ÿ”ด Server ended with error +} + +Greetings.findOne({ name: 'John' }); // ๐Ÿ—‘๏ธ Data is NOT available +``` + +#### stubPromise + +```javascript +await Meteor.callAsync('greetUser', 'John').stubPromise; + +// ๐Ÿ”ต Client simulation +Greetings.findOne({ name: 'John' }); // ๐Ÿงพ Data is available (Optimistic-UI) +``` + +#### stubPromise and serverPromise + +```javascript +const { stubPromise, serverPromise } = Meteor.callAsync('greetUser', 'John'); + +await stubPromise; + +// ๐Ÿ”ต Client simulation +Greetings.findOne({ name: 'John' }); // ๐Ÿงพ Data is available (Optimistic-UI) + +try { + await serverPromise; + // ๐ŸŸข Server ended with success +} catch(e) { + console.error("Error:", error.reason); // ๐Ÿ”ด Server ended with error +} + +Greetings.findOne({ name: 'John' }); // ๐Ÿ—‘๏ธ Data is NOT available +``` + +#### Meteor 2.x contrast + +For those familiar with legacy Meteor 2.x, the handling of client simulation and server response was managed using fibers, as explained in the following section. This comparison illustrates how async inclusion with standard promises has transformed the way Meteor operates in modern versions. + +``` javascript +Meteor.call('greetUser', 'John', function(error, result) { + if (error) { + console.error("Error:", error.reason); // ๐Ÿ”ด Server ended with error + } else { + console.log("Result:", result); // ๐ŸŸข Server ended with success + } + + Greetings.findOne({ name: 'John' }); // ๐Ÿ—‘๏ธ Data is NOT available +}); + +// ๐Ÿ”ต Client simulation +Greetings.findOne({ name: 'John' }); // ๐Ÿงพ Data is available (Optimistic-UI) +``` +