Introduction
This topic is more for more own records, and covers various design patterns of using explicit Promise chaining of the new API’s asynchronous calls. In each example I have elided using a catch statement because I want to implicitly log errors in the Bubble server logs, which the catch statement will block.
Parallel List Loading
In this example we will load two lists asynchronously in parallel, leveraging Promise.all() to load the lists from properties.listone and properties.listtwo:
// Hold the lists
const lists = [Promise.resolve([]), Promise.resolve([])];
// Asynchronously load an array of the first list
if (properties.listone) {
lists[0] = lists[0]
.then((_) => { return properties.listone.length(); })
.then((n) => { return properties.listone.get(0, n); });
}
// Asynchronously load an array of the second list
if (properties.listtwo) {
lists[1] = lists[1]
.then((_) => { return properties.listtwo.length(); })
.then((n) => { return properties.listtwo.get(0, n); });
}
// Access when both are done
const keepgoing = Promise.all(lists)
.then(([xs, ys]) => { /* Do something with the two lists */ });
JSON POST
In this example we will POST to a secure JSON endpoint, assuming the plugin has the bearer token environment variable under context.token and the third party endpoint under context.url:
// Specify the fetch options
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + context.token
}
body: JSON.stringify(mydata)
};
// Parse the JSON from the POST
const response = fetch(context.url, options)
.then((r) => { return r.json(); })
.then((j) => { /* Do something with the parsed data */ });
Binary GET
In this example we will GET the binary of a file specified by the plugin parameter properties.url:
const options = {
method: "GET",
headers: { "Accept": "application/octet-stream" }
};
// Retrieve the file
const response = fetch(properties.url, options)
.then((r) => { return r.arrayBuffer(); })
.then((a) => { /* Do something with the raw binary */ });
Summation
Those were the three most common use cases I have encountered while updating my plugins. I hope someone finds these useful. I favour using explicit promising chaining because it forces me to reason through and define the exact dependencies between asynchronous calls, rather than spraying and praying awaits everywhere.
