Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

Higher Order Promises

node v10.24.1
version: 1.0.0
endpointsharetweet
// Let's set up some fake asynchronous tasks so we can see what we're dealing with. var getJSON = require("async-get-json"); var higherOrderPromise = require("@liveramp/higher-order-promise") // Get the current position of the ISS Space Station. function getISSPosition() { return getJSON("http://api.open-notify.org/iss-now.json"); } // Pretend to asynchronously fetch a name let simpleAsyncName = Promise.resolve("Frank") let result = higherOrderPromise.HigherOrderPromise.of({ issData: getISSPosition(), name: simpleAsyncName }).then((data) => { // Data holds the resolved promise values, and maintains type information, // allowing for simple mutation and aggregation return { name: data.name + " Zappa", issPosition: data.issData.iss_position } }) await result.yield()
// Ok, that's kinda neat. But why tho? // Well, these promises work in parallel. Let's demonstrate this! // This function resolves after a passed "timeout" function slowPromise(identifier, timeout, result) { return new Promise((resolve) => { console.log(`Starting promise: ${identifier}`) setTimeout(() => {console.log(`Ending promise: ${identifier}`); resolve(result)}, timeout) }) } // Here's what await does on its own - you'll see output one at a time. Start, End, Start, End. let result1 = await slowPromise("1", 1000, 10); let result2 = await slowPromise("2", 1000, 20); result1 + result2
// If the promises aren't related, why do them in order? // Of course, Promises support parallelization natively. await Promise.all([slowPromise("1", 1000, 10), slowPromise("2", 1000, 20)])
// But we get back an array, so we have to wrangle indices manally. There isn't really a nice way // of naming these parallel operations. // So let's do it with HigherOrderPromise! await higherOrderPromise.HigherOrderPromise.of({ userName: slowPromise("userName", 1000, "Matt"), numberOfCats: slowPromise("numberOfCats", 1000, Number.MAX_VALUE) }).yield()
// Best of both worlds - parallelize, but also identify. // And that's not all! (There's more?) await higherOrderPromise.HigherOrderPromise.of({ userName: slowPromise("userName", 1000, "Matt"), numberOfCats: slowPromise("numberOfCats", 1000, Number.MAX_VALUE) }).then((data) => { // Use your imagination here, perhaps we want to get the user age for our user name. // We can mix resolved and unresolved promises! return { name: data.userName, age: slowPromise("userAgeRetriever", 1000, 32), // ouch so old. numberOfCats: data.numberOfCats } }).yield()
Loading…

no comments

    sign in to comment