[{"data":1,"prerenderedAt":89},["ShallowReactive",2],{"course-en-currying-and-asynchrony":3},{"lesson":4,"number":80,"prev":81,"next":85},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":52,"exercises":61},"currying-and-asynchrony",{"ru":7,"en":8},"","Currying and asynchrony (evolution)",{"ru":7,"en":10},"Currying in asynchronous JavaScript: specialized request functions and a pipeAsync that waits for promises by itself and sends every error to a single catch.",{"ru":7,"en":12},"Learn to apply currying to asynchronous code: build specialized request functions and chain asynchronous steps into a pipeline that waits for promises by itself.",[14,17,25,30,32,34,38,40,42,45,47,49],{"type":15,"ru":7,"en":16},"text","Currying can be used effectively in asynchronous programming.",{"type":18,"ordered":19,"items":20},"list",true,[21,23],{"ru":7,"en":22},"Creating specialized functions",{"ru":7,"en":24},"We will defeat \"callback hell\" without promises",{"type":26,"noRun":27,"code":28},"code","network",{"ru":7,"en":29},"\u002F\u002F  Let's create a base function for requests\n\u002F\u002F baseFetch :: String -> String -> a -> Promise\nconst baseFetch = (baseUrl) =>\n                    (params) =>\n                    (config = {}) =>\n                      fetch(`${baseUrl}\u002F${params}`, config)\n\n\nconst BASE_URL = 'https:\u002F\u002Fexample.com'\n\u002F\u002F bound to the base url\nconst useFetch = baseFetch (BASE_URL)\n\n\u002F\u002F create two specialized functions\n\u002F\u002F get the list of all users\nconst getAllUser = useFetch ('all-users')\n\u002F\u002F get the list of all books\nconst getAllBooks = useFetch ('all-books')\n\n\u002F\u002F now we can call the functions and get the data\ngetAllUser ().then(console.log)\ngetAllBooks ().then(console.log)\n\n\u002F\u002F you can add authorization tokens\n\u002F\u002F in a separate closure if needed\n\u002F\u002F xFetch :: String -> b -> String -> a -> Promise\nconst xFetch = (baseUrl) =>\n          (headers) =>\n          (params) =>\n          (config = {}) =>\n            fetch(`${baseUrl}\u002F${params}`, {\n              ...config,\n              \u002F\u002F merge the shared headers (with the token) with the request headers\n              \u002F\u002F so that config.headers does not replace them entirely\n              headers: { ...headers, ...config.headers },\n            })\n\nconst token = 'xxx'\n\u002F\u002F bound to the base url and to the headers at once\nconst useXFetch = xFetch (BASE_URL) ({\n  'Content-Type': 'application\u002Fjson',\n  'authorization': `Bearer ${token}`,\n})\n\n\u002F\u002F create two specialized functions\n\u002F\u002F get the list of all users\nconst getAllUserX = useXFetch ('all-users')\n\u002F\u002F get the list of all books\nconst getAllBooksX = useXFetch ('all-books')",{"type":15,"ru":7,"en":31},"Now below we will show two examples.",{"type":15,"ru":7,"en":33},"The first piece of code will be imperative and callback-based, while the second will use currying and closures without promises.",{"type":26,"noRun":35,"code":36},"dom",{"ru":7,"en":37},"\u002F\u002F  code that \"smells bad\"\n\n\u002F\u002F create a request function based on XMLHttpRequest:\n\u002F\u002F it works with events, without promises\n\u002F\u002F (we could wrap it in promises, of course, but today's topic is currying)\n\nconst fetchXML = (url, callback) => {\n  const req = new XMLHttpRequest()\n  req.addEventListener('load', () => {\n    const data = JSON.parse(req.responseText)\n    callback(data)\n  })\n  req.open('GET', url)\n  req.send()\n}\n\n\n\u002F\u002F What we want\n\u002F\u002F 1. When the \"details\" button of a user is clicked,\n\u002F\u002F we read the user's slug from the data attribute\n\u002F\u002F 2. Using the slug, we request the list of reviews\n\u002F\u002F 3. We take the slug of the latest review (first in the list) and make a request\n\u002F\u002F 4. We get the review details and take its text\n\u002F\u002F API: \u002Freviews\u002F\u003Cuser slug> returns an array of reviews (latest first),\n\u002F\u002F \u002Freview-info\u002F\u003Creview slug> returns a review with a text field\n\n\u002F\u002F the text we will show\nvar textReview = ''\n\n\u002F\u002F use event delegation on the whole container with the buttons\ndocument.getElementById('users-wrapper')\n  .addEventListener('click', (e) => {\n    \u002F\u002F get the element\n    const el = e.target\n\n    \u002F\u002F if the click is not on a user button, ignore it\n    if(!el.classList.contains('user-btn')) {\n      return\n    }\n\n    \u002F\u002F get the user's slug from the button\n    const slugUser = el.dataset.slug \u002F\u002F 'xksdfjdkhfd' is the slug\n\n    \u002F\u002F make sure there is a slug\n    if(!slugUser) {\n      return\n    }\n\n    \u002F\u002F get the list of reviews by the user's slug\n    fetchXML('https:\u002F\u002Fexample.com\u002Freviews\u002F' + slugUser, (reviews) => {\n      \u002F\u002F get the slug of the latest review\n      const slugFirstReview = reviews[0].slug\n\n      \u002F\u002F request the review details\n      fetchXML('https:\u002F\u002Fexample.com\u002Freview-info\u002F' + slugFirstReview, (review) => {\n        textReview = review.text\n      })\n    })\n  })",{"type":15,"ru":7,"en":39},"We will use currying without promises and defeat \"callback hell\".",{"type":15,"ru":7,"en":41},"Let's refactor our code.",{"type":26,"noRun":35,"code":43},{"ru":7,"en":44},"\u002F\u002F  declarative code\n\u002F\u002F ==== NOTE: many of these helper functions already\n\u002F\u002F ==== exist in ready-made libraries;\n\u002F\u002F ==== we often write them here for learning purposes\n\n\u002F\u002F create a request function based on XMLHttpRequest:\n\u002F\u002F it works with events, without promises\n\u002F\u002F (we could wrap it in promises, of course, but today's topic is currying)\n\n\u002F\u002F fetchXML :: String -> String -> String -> (a -> *) -> XMLHttpRequest\nconst fetchXML = (baseUrl) => (params) => (id) => (callback) => {\n  const req = new XMLHttpRequest()\n  req.addEventListener('load', () => callback(JSON.parse(req.responseText)))\n  req.open('GET', `${baseUrl}\u002F${params}\u002F${id}`)\n  req.send()\n  return req\n}\n\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)\n\n\n\u002F\u002F let's build specialized functions on top of the function above\nconst BASE_URL = 'https:\u002F\u002Fexample.com'\nconst REVIEWS = 'reviews'\nconst REVIEW_INFO = 'review-info'\n\n\u002F\u002F a function with the base path fixed\nconst fetchBaseUrl = fetchXML(BASE_URL)\n\n\u002F\u002F a function that gets the list of reviews\nconst getReviews = fetchBaseUrl(REVIEWS)\n\n\u002F\u002F a function that gets the details of a specific review\nconst getReviewInfo = fetchBaseUrl(REVIEW_INFO)\n\n\u002F\u002F now let's create a helper for the click event\n\u002F\u002F so that we can use it in function composition\n\u002F\u002F clickElement :: Element -> (Event -> *) -> Undefined\nconst clickElement = (element) =>\n                      (callback) =>\n                        element.addEventListener('click', callback)\n\n\u002F\u002F What we want\n\u002F\u002F 1. When the \"details\" button of a user is clicked,\n\u002F\u002F we read the user's slug from the data attribute\n\u002F\u002F 2. Using the slug, we request the list of reviews\n\u002F\u002F 3. We take the slug of the latest review (first in the list) and make a request\n\u002F\u002F 4. We get the review details and take its text\n\u002F\u002F API: \u002Freviews\u002F\u003Cuser slug> returns an array of reviews (latest first),\n\u002F\u002F \u002Freview-info\u002F\u003Creview slug> returns a review with a text field\n\n\u002F\u002F head :: [a] -> a\nconst head = (arr) => arr[0]\n\n\u002F\u002F prop :: String -> a -> b\nconst prop = (prop) => (obj) => obj[prop]\n\n\u002F\u002F the text we will show\nvar textReview = ''\n\n\u002F\u002F get the container with the buttons\nconst btnWrapper =  document.getElementById('users-wrapper')\n\n\u002F\u002F run the composition right away\nclickElement (btnWrapper) (pipe(\n  (e) => e?.target, \u002F\u002F get the element\n  (el) => el?.dataset?.slug, \u002F\u002F get the data attribute\n  (slugUser) => getReviews (slugUser) ( \u002F\u002F request all reviews\n        pipe(\n          head, \u002F\u002F take the first review\n          prop('slug'), \u002F\u002F and its slug\n          (slug) => getReviewInfo (slug) ( \u002F\u002F request the review details by the slug\n            (review) => {\n              textReview = prop ('text') (review) \u002F\u002F write the result into a global variable\n            })\n        )\n      )\n))",{"type":15,"ru":7,"en":46},"I'll admit it: the smell of bad code hasn't gone away. On top of that, this version lost the checks from the first one: that the click was on a user button and that the button has a slug. So a click outside a button sends a request to \u002Freviews\u002Fundefined, and errors aren't handled here at all. We'll fix both shortcomings in the next version.",{"type":15,"ru":7,"en":48},"What if we add the power of promises to the code above and transform it?",{"type":26,"noRun":35,"code":50},{"ru":7,"en":51},"\u002F\u002F  Now let's get down to business\n\u002F\u002F copy clickElement, btnWrapper, head, prop and textReview from the previous example;\n\u002F\u002F BASE_URL, REVIEWS, REVIEW_INFO, getReviews and getReviewInfo are declared here again,\n\u002F\u002F so the two blocks can't be run together as a single piece\n\u002F\u002F let's rewrite our data-fetching function\n\u002F\u002F so that it returns a promise itself\n\n\u002F\u002F fetchClassic :: String -> String -> String -> Promise\nconst fetchClassic = (baseUrl) =>\n                        (params) =>\n                        (id) =>\n                        fetch (`${baseUrl}\u002F${params}\u002F${id}`)\n                          .then ((res) => {\n                            \u002F\u002F fetch does not reject on responses like 404 or 500,\n                            \u002F\u002F so we check the status ourselves\n                            if (!res.ok) throw new Error(`HTTP ${res.status}`)\n                            return res.json()\n                          })\n\nconst BASE_URL = 'https:\u002F\u002Fexample.com'\nconst REVIEWS = 'reviews'\nconst REVIEW_INFO = 'review-info'\n\n\u002F\u002F get the list of reviews and the details of a review\nconst getReviews = fetchClassic (BASE_URL) (REVIEWS)\nconst getReviewInfo = fetchClassic (BASE_URL) (REVIEW_INFO)\n\n\n\u002F\u002F We'll have a super pipe that waits for promises\n\u002F\u002F under the hood: once a step returns a promise,\n\u002F\u002F the next steps go through then, and the result is a promise too\n\u002F\u002F pipeAsync :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipeAsync = (...fns) => (x) => fns.reduce((v, f) => {\n  return v instanceof Promise\n    ? v.then(f)\n    : f(v)\n}, x)\n\n\u002F\u002F get the text of the user's latest review by the user's slug\n\u002F\u002F loadReviewText :: String -> Promise String\nconst loadReviewText = pipeAsync(\n  getReviews, \u002F\u002F request all reviews\n  head, \u002F\u002F take the first review\n  prop('slug'), \u002F\u002F and its slug\n  getReviewInfo, \u002F\u002F request the review details by the slug\n  prop('text'), \u002F\u002F take the text field\n  (text) => textReview = text, \u002F\u002F store it in the global variable\n)\n\n\u002F\u002F the same checks as in the first version: the click is on a user button\n\u002F\u002F and the button has a slug; other clicks are ignored\n\u002F\u002F onUserButton :: (String -> *) -> Event -> Undefined\nconst onUserButton = (handler) => (e) => {\n  const el = e.target\n  if (!el.classList.contains('user-btn') || !el.dataset.slug) {\n    return\n  }\n  handler(el.dataset.slug)\n}\n\n\u002F\u002F run the improved version:\n\u002F\u002F pipeAsync handles promises under the hood, and an error at any step\n\u002F\u002F (network, response status, empty list of reviews) ends up in catch\nclickElement (btnWrapper) (onUserButton ((slug) =>\n  loadReviewText (slug)\n    .catch ((error) => console.error('Failed to load the review:', error.message))\n))",[53,55,57,59],{"ru":7,"en":54},"The curried base request function baseFetch keeps the base URL and the path in closures, and specialized functions such as getAllUser and getAllBooks are built from it through calls. Headers with a token can be kept in a separate closure, as in xFetch, from which getAllUserX and getAllBooksX are built.",{"ru":7,"en":56},"Currying and pipe without promises make callback-based code declarative, but the smell of bad code doesn't go away: errors aren't handled in that version at all.",{"ru":7,"en":58},"pipeAsync waits for promises by itself: once a step returns a promise, the next steps go through then, and the result is a promise too.",{"ru":7,"en":60},"In a promise-based pipeline, an error at any step — the network, the response status, an empty list — ends up in a single catch.",[62,71],{"task":63,"starter":65,"solution":67,"expected":69},{"ru":7,"en":64},"In the starter, fakeFetch simulates a request: after 5 ms it returns the response stored in DB under the URL, or rejects the promise if there is no such URL. Write a curried base function createRequest :: String -> String -> Number -> Promise Object that takes a base URL, a resource and an id. Fix the base URL https:\u002F\u002Fexample.com in it and derive the specialized functions getUser and getBook. Print the name of user 1 and the title of book 7.",{"ru":7,"en":66},"\u002F\u002F fake server data: URL -> response\nconst DB = {\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F1': { name: 'John', favoriteBook: 7 },\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F2': { name: 'Anna', favoriteBook: 3 },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F3': { title: 'Functional-Light JavaScript' },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F7': { title: 'Structure and Interpretation of Computer Programs' },\n}\n\n\u002F\u002F simulated request: after 5 ms it returns the response for the URL\n\u002F\u002F or rejects the promise if there is no such URL\n\u002F\u002F fakeFetch :: String -> Promise Object\nconst fakeFetch = (url) => new Promise((resolve, reject) => {\n  setTimeout(() => {\n    if (url in DB) resolve(DB[url])\n    else reject(new Error(`404 ${url}`))\n  }, 5)\n})\n\n\u002F\u002F your code",{"ru":7,"en":68},"\u002F\u002F fake server data: URL -> response\nconst DB = {\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F1': { name: 'John', favoriteBook: 7 },\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F2': { name: 'Anna', favoriteBook: 3 },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F3': { title: 'Functional-Light JavaScript' },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F7': { title: 'Structure and Interpretation of Computer Programs' },\n}\n\n\u002F\u002F simulated request: after 5 ms it returns the response for the URL\n\u002F\u002F or rejects the promise if there is no such URL\n\u002F\u002F fakeFetch :: String -> Promise Object\nconst fakeFetch = (url) => new Promise((resolve, reject) => {\n  setTimeout(() => {\n    if (url in DB) resolve(DB[url])\n    else reject(new Error(`404 ${url}`))\n  }, 5)\n})\n\n\u002F\u002F createRequest :: String -> String -> Number -> Promise Object\nconst createRequest = (baseUrl) => (resource) => (id) => fakeFetch(`${baseUrl}\u002F${resource}\u002F${id}`)\n\n\u002F\u002F the base URL is kept in the closure\nconst api = createRequest('https:\u002F\u002Fexample.com')\n\n\u002F\u002F specialized functions: the resource is fixed too, they wait only for an id\nconst getUser = api('users')\nconst getBook = api('books')\n\ngetUser(1).then((user) => console.log(user.name))\ngetBook(7).then((book) => console.log(book.title))",{"ru":7,"en":70},"John\nStructure and Interpretation of Computer Programs",{"task":72,"starter":74,"solution":76,"expected":78},{"ru":7,"en":73},"The starter already has getUser and getBook from the first exercise. Write pipeAsync, a pipe that waits for promises by itself, and use it to build loadFavoriteBook :: Number -> Promise String: request the user by id, take the favoriteBook field, request that book and return its title. The output is already in the starter: showFavoriteBook prints the title of user 2's favorite book, then tries user 5, who is not in DB, and handles the error with catch.",{"ru":7,"en":75},"\u002F\u002F fake server data: URL -> response\nconst DB = {\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F1': { name: 'John', favoriteBook: 7 },\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F2': { name: 'Anna', favoriteBook: 3 },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F3': { title: 'Functional-Light JavaScript' },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F7': { title: 'Structure and Interpretation of Computer Programs' },\n}\n\n\u002F\u002F fakeFetch :: String -> Promise Object\nconst fakeFetch = (url) => new Promise((resolve, reject) => {\n  setTimeout(() => {\n    if (url in DB) resolve(DB[url])\n    else reject(new Error(`404 ${url}`))\n  }, 5)\n})\n\n\u002F\u002F createRequest :: String -> String -> Number -> Promise Object\nconst createRequest = (baseUrl) => (resource) => (id) => fakeFetch(`${baseUrl}\u002F${resource}\u002F${id}`)\nconst api = createRequest('https:\u002F\u002Fexample.com')\nconst getUser = api('users')\nconst getBook = api('books')\n\n\u002F\u002F your code: pipeAsync and loadFavoriteBook\n\n\u002F\u002F an error at any step ends up in catch\n\u002F\u002F showFavoriteBook :: Number -> Promise Undefined\nconst showFavoriteBook = (userId) =>\n  loadFavoriteBook(userId)\n    .then((title) => console.log(title))\n    .catch((error) => console.log(`Request failed: ${error.message}`))\n\n\u002F\u002F user 2 first, then user 5, who does not exist\nshowFavoriteBook(2).then(() => showFavoriteBook(5))",{"ru":7,"en":77},"\u002F\u002F fake server data: URL -> response\nconst DB = {\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F1': { name: 'John', favoriteBook: 7 },\n  'https:\u002F\u002Fexample.com\u002Fusers\u002F2': { name: 'Anna', favoriteBook: 3 },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F3': { title: 'Functional-Light JavaScript' },\n  'https:\u002F\u002Fexample.com\u002Fbooks\u002F7': { title: 'Structure and Interpretation of Computer Programs' },\n}\n\n\u002F\u002F fakeFetch :: String -> Promise Object\nconst fakeFetch = (url) => new Promise((resolve, reject) => {\n  setTimeout(() => {\n    if (url in DB) resolve(DB[url])\n    else reject(new Error(`404 ${url}`))\n  }, 5)\n})\n\n\u002F\u002F createRequest :: String -> String -> Number -> Promise Object\nconst createRequest = (baseUrl) => (resource) => (id) => fakeFetch(`${baseUrl}\u002F${resource}\u002F${id}`)\nconst api = createRequest('https:\u002F\u002Fexample.com')\nconst getUser = api('users')\nconst getBook = api('books')\n\n\u002F\u002F prop :: String -> a -> b\nconst prop = (key) => (obj) => obj[key]\n\n\u002F\u002F a pipe that waits for promises by itself: once a step returns a promise,\n\u002F\u002F the next steps go through then\n\u002F\u002F pipeAsync :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipeAsync = (...fns) => (x) => fns.reduce((v, f) => (v instanceof Promise ? v.then(f) : f(v)), x)\n\n\u002F\u002F loadFavoriteBook :: Number -> Promise String\nconst loadFavoriteBook = pipeAsync(\n  getUser, \u002F\u002F request the user\n  prop('favoriteBook'), \u002F\u002F the id of their favorite book\n  getBook, \u002F\u002F request the book\n  prop('title'), \u002F\u002F its title\n)\n\n\u002F\u002F an error at any step ends up in catch\n\u002F\u002F showFavoriteBook :: Number -> Promise Undefined\nconst showFavoriteBook = (userId) =>\n  loadFavoriteBook(userId)\n    .then((title) => console.log(title))\n    .catch((error) => console.log(`Request failed: ${error.message}`))\n\n\u002F\u002F user 2 first, then user 5, who does not exist\nshowFavoriteBook(2).then(() => showFavoriteBook(5))",{"ru":7,"en":79},"Functional-Light JavaScript\nRequest failed: 404 https:\u002F\u002Fexample.com\u002Fusers\u002F5",12,{"slug":82,"title":83},"point-free",{"ru":7,"en":84},"Point-free style",{"slug":86,"title":87},"recursion",{"ru":7,"en":88},"Recursion",1792684724218]