#promise.all js
Explore tagged Tumblr posts
codewithnazam · 1 year ago
Text
Javascript Promise all: You Didn't Know You Needed!
In JavaScript, Promise all is a method that takes an array of promises and returns a single promise. This new promise is fulfilled with an array of the fulfilled values of the original promises, in the same order as the promises passed to Promise.all. If any of the input promises is rejected, the whole Promise.all is rejected with the reason of the first rejected promise. "If you're new to the…
Tumblr media
View On WordPress
0 notes
weva-cloud · 2 years ago
Text
特定ページ上の特定クラスのリンク先URLを収集し、 フロントJSでそれらのHTMLを開いて、 それぞれのページ上でさらに特定クラスのリンク先URLを集めるためのスクリプト例:
Tumblr media
```js
var links = Array.from(document.querySelectorAll('a.target-class')).map(a => a.href);
var promiseResponseTexts = await Promise.all( links.map(link => fetch(link)) ) .then(res => res.map(r => r.text()));
var responseTexts = await Promise.all(promiseResponseTexts);
var nextPageTargetLinks = responseTexts.map(text => { var parser = new DOMParser(); var doc = parser.parseFromString(text, 'text/html'); return doc.querySelector('a.next-page-target-class')?.href; });
console.log(nextPageTargetLinks)
```
これを応用するとフロントエンドJavaScriptだけで柔軟なスクレイピングが可能です。
0 notes
psychicanchortimemachine · 4 years ago
Text
JavaScript Async/Await Explained in 10 Minutes
For the longest of your time JavaScript developers had to trust callbacks for operating with asynchronous code. As a result, several folks have experienced recall hell and also the horror one goes through once Janus-faced with functions wanting like this.
Thankfully, then (or ought to we are saying .then()) came guarantees. They offered a way additional organized various to callbacks and most of the community quickly captive on to victimization them instead.
Now, with the foremost recent addition of Async/Await, writing JavaScript code is getting ready to get even better!
What is Async/Await?
Async/Await could be a long anticipated JavaScript feature that produces operating with asynchronous functions rather more pleasurable and easier to grasp. It devolves on high of guarantees and is compatible with all existing Promise-based genus Apis.  The name comes from async and await - the two keywords that will help us clean up our asynchronous code:
Async - declares an asynchronous function(async function someName(){...}).
Automatically transforms a regular function into a Promise.
When called async functions resolve with whatever is returned in their body.
Async functions enable the use of await.
Await - pauses the execution of async functions.(var result = await someAsyncCall();).
When placed in front of a Promise call, await forces the rest of the code to wait until that Promise finishes and returns a result.
Await works only with Promises, it does not work with callbacks.
Await can only be used inside async functions.
Here could be a straightforward example that may hopefully clear things up: Let's say we wish to urge some JSON file from our server. We’ll write a function that uses the axios library and sends a hypertext transfer protocol GET.
We’ve to attend for the server to retort, thus naturally this hypertext transfer protocol request are going to be asynchronous. Below we are able to see an equivalent operate enforced double. Initial with guarantees, then a second time mistreatment Async/Await.
// Promise approach function getJSON(){  // To make the function blocking we manually create a Promise.   return new Promise( function(resolve) {   axios.get('https://tutorialzine.com/misc/files/example.json')        .then( function(json) {               // The data from the request is available in a .then block      // We return the result using resolve.        resolve(json);           });  });   }    // Async/Await approach    // The async keyword will automatically create a new Promise and return it. async function getJSONAsync(){     // The await keyword saves us from having to write a .then() block.   let json = await axios.get('https://tutorialzine.com/misc/files/example.json');    // The result of the GET request is available in the json variable.  // We return it just like in a regular synchronous function.   return json;  }
It's pretty clear that the Async/Await version of the code is much shorter and easier to read. Other than the syntax used, both functions are completely identical - they both return Promises and resolve with the JSON response from axios. We can call our async function like this:
getJSONAsync().then( function(result) { // Do something with result. });
So, does Async/Await make promises obsolete?
No, not at all. once operating with Async/Await we tend to ar still victimisation guarantees beneath the hood. a decent understanding of guarantees can really assist you within the long-standing time and is very counseled.
There are even uses cases wherever Async/Await does not cut it and that we need to return to guarantees for facilitate. One such situation is after we ought to build multiple freelance asynchronous calls and look forward to all of them to end.
If we tend to attempt to try this with async and expect, the subsequent can happen:
async function getABC() { let A = await getValueA(); // getValueA takes 2 second to finish let B = await getValueB(); // getValueB takes 4 second to finish let C = await getValueC(); // getValueC takes 3 second to finish return A*B*C; }
Each wait decision can sit up for the previous one to come back a result. Since we have a tendency to do one go into a time the complete operate can take nine seconds from begin to complete (2+4+3).  This is not associate best answer, since the 3 variables A, B, and C are not addicted to one another. In alternative words we do not have to be compelled to grasp the worth of A before we have a tendency to get B. we are able to get them at a similar time and shave off a number of seconds of waiting. To send all requests at a similar time a Promise.all() is needed.This may ensure we have a tendency to still have all the results before continued, however the asynchronous calls are firing in parallel, not one when another.
async function getABC() { // Promise.all() allows us to send all requests at the same time. let results = await Promise.all([ getValueA, getValueB, getValueC ]); return results.reduce((total,value) => total * value); }
This way the operate can take a lot of less time. The getValueA and getValueC calls can have already finished by the time getValueB ends. rather than a total of the days, we'll effectively scale back the execution to the time of the slowest request (getValueB - four seconds).This way the function will take much less time.
Handling Errors in Async/Await
Another great thing about Async/Await is that it allows us to catch any unexpected errors in a good old try/catch block. We just need to wrap our await calls like this:
async function doSomethingAsync(){ try { // This async call may fail. let result = await someAsyncCall(); } catch(error) { // If it does we will catch the error here. } }
The catch clause can handle errors provoked by the anticipated asynchronous calls or the other failing code we tend to might have written within the attempt block. If the situation requires it, we can also catch errors upon executing the async function. Since all async functions return Promises we can simply include a .catch() event handler when calling them.
// Async function without a try/catch block. async function doSomethingAsync(){ // This async call may fail. let result = await someAsyncCall(); return result; } // We catch the error upon calling the function. doSomethingAsync(). .then(successHandler) .catch(errorHandler);
It's important to choose which method of error handling you prefer and stick to it. Using both try/catch and .catch() at the same time will most probably lead to problems.
Browser Support Async/Await is already on the market in most major browsers. This excludes solely IE11 - all different vendors can acknowledge your async/await code while not the requirement of external libraries.
Node developers may get pleasure from the improved async flow as long as they're on Node eight or newer. It ought to become LTS later this year.
If this compatibility does not satisfy you, there are many JS transpilers like Babel and matter, and also the Node.js library asyncawait that provide their own cross-platform versions of the feature.
Conclusion
With the addition of Async/Await the JavaScript language takes a large breakthrough in terms of code readability and easy use. the flexibility to put in writing asynchronous code that resembles regular synchronous functions are appreciated by each beginners to JavaScript and veteran coders.
Async on MDN
Await on MDN
Async/Await: The Hero JavaScript Deserved
Where Did Async/Await Come from and Why Use It?
We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs. As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
0 notes
lakhwanabhishek · 4 years ago
Text
JavaScript Async/Await Explained in 10 Minutes
For the longest of your time JavaScript developers had to trust callbacks for operating with asynchronous code. As a result, several folks have experienced recall hell and also the horror one goes through once Janus-faced with functions wanting like this.
Thankfully, then (or ought to we are saying .then()) came guarantees. They offered a way additional organized various to callbacks and most of the community quickly captive on to victimization them instead.
Now, with the foremost recent addition of Async/Await, writing JavaScript code is getting ready to get even better!
What is Async/Await?
Async/Await could be a long anticipated JavaScript feature that produces operating with asynchronous functions rather more pleasurable and easier to grasp. It devolves on high of guarantees and is compatible with all existing Promise-based genus Apis.  The name comes from async and await - the two keywords that will help us clean up our asynchronous code:
Async - declares an asynchronous function(async function someName(){...}).
Automatically transforms a regular function into a Promise.
When called async functions resolve with whatever is returned in their body.
Async functions enable the use of await.
Await - pauses the execution of async functions.(var result = await someAsyncCall();).
When placed in front of a Promise call, await forces the rest of the code to wait until that Promise finishes and returns a result.
Await works only with Promises, it does not work with callbacks.
Await can only be used inside async functions.
Here could be a straightforward example that may hopefully clear things up: Let's say we wish to urge some JSON file from our server. We’ll write a function that uses the axios library and sends a hypertext transfer protocol GET.
We’ve to attend for the server to retort, thus naturally this hypertext transfer protocol request are going to be asynchronous. Below we are able to see an equivalent operate enforced double. Initial with guarantees, then a second time mistreatment Async/Await.
// Promise approach function getJSON(){  // To make the function blocking we manually create a Promise.   return new Promise( function(resolve) {   axios.get('https://tutorialzine.com/misc/files/example.json')        .then( function(json) {               // The data from the request is available in a .then block      // We return the result using resolve.        resolve(json);           });  });   }    // Async/Await approach    // The async keyword will automatically create a new Promise and return it. async function getJSONAsync(){     // The await keyword saves us from having to write a .then() block.   let json = await axios.get('https://tutorialzine.com/misc/files/example.json');    // The result of the GET request is available in the json variable.  // We return it just like in a regular synchronous function.   return json;  }
It's pretty clear that the Async/Await version of the code is much shorter and easier to read. Other than the syntax used, both functions are completely identical - they both return Promises and resolve with the JSON response from axios. We can call our async function like this:
getJSONAsync().then( function(result) { // Do something with result. });
So, does Async/Await make promises obsolete?
No, not at all. once operating with Async/Await we tend to ar still victimisation guarantees beneath the hood. a decent understanding of guarantees can really assist you within the long-standing time and is very counseled.
There are even uses cases wherever Async/Await does not cut it and that we need to return to guarantees for facilitate. One such situation is after we ought to build multiple freelance asynchronous calls and look forward to all of them to end.
If we tend to attempt to try this with async and expect, the subsequent can happen:
async function getABC() { let A = await getValueA(); // getValueA takes 2 second to finish let B = await getValueB(); // getValueB takes 4 second to finish let C = await getValueC(); // getValueC takes 3 second to finish return A*B*C; }
Each wait decision can sit up for the previous one to come back a result. Since we have a tendency to do one go into a time the complete operate can take nine seconds from begin to complete (2+4+3).  This is not associate best answer, since the 3 variables A, B, and C are not addicted to one another. In alternative words we do not have to be compelled to grasp the worth of A before we have a tendency to get B. we are able to get them at a similar time and shave off a number of seconds of waiting. To send all requests at a similar time a Promise.all() is needed.This may ensure we have a tendency to still have all the results before continued, however the asynchronous calls are firing in parallel, not one when another.
async function getABC() { // Promise.all() allows us to send all requests at the same time. let results = await Promise.all([ getValueA, getValueB, getValueC ]); return results.reduce((total,value) => total * value); }
This way the operate can take a lot of less time. The getValueA and getValueC calls can have already finished by the time getValueB ends. rather than a total of the days, we'll effectively scale back the execution to the time of the slowest request (getValueB - four seconds).This way the function will take much less time.
Handling Errors in Async/Await
Another great thing about Async/Await is that it allows us to catch any unexpected errors in a good old try/catch block. We just need to wrap our await calls like this:
async function doSomethingAsync(){ try { // This async call may fail. let result = await someAsyncCall(); } catch(error) { // If it does we will catch the error here. } }
The catch clause can handle errors provoked by the anticipated asynchronous calls or the other failing code we tend to might have written within the attempt block. If the situation requires it, we can also catch errors upon executing the async function. Since all async functions return Promises we can simply include a .catch() event handler when calling them.
// Async function without a try/catch block. async function doSomethingAsync(){ // This async call may fail. let result = await someAsyncCall(); return result; } // We catch the error upon calling the function. doSomethingAsync(). .then(successHandler) .catch(errorHandler);
It's important to choose which method of error handling you prefer and stick to it. Using both try/catch and .catch() at the same time will most probably lead to problems.
Browser Support Async/Await is already on the market in most major browsers. This excludes solely IE11 - all different vendors can acknowledge your async/await code while not the requirement of external libraries.
Node developers may get pleasure from the improved async flow as long as they're on Node eight or newer. It ought to become LTS later this year.
If this compatibility does not satisfy you, there are many JS transpilers like Babel and matter, and also the Node.js library asyncawait that provide their own cross-platform versions of the feature.
Conclusion
With the addition of Async/Await the JavaScript language takes a large breakthrough in terms of code readability and easy use. the flexibility to put in writing asynchronous code that resembles regular synchronous functions are appreciated by each beginners to JavaScript and veteran coders.
Async on MDN
Await on MDN
Async/Await: The Hero JavaScript Deserved
Where Did Async/Await Come from and Why Use It?
We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs. As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
#b2b ecommerce
#b2bsales
#b2bservices
#b2b seo
#Ecommerce
0 notes
secretcupcakesublime · 4 years ago
Text
JavaScript Async/Await Explained in 10 Minutes
For the longest of your time JavaScript developers had to trust callbacks for operating with asynchronous code. As a result, several folks have experienced recall hell and also the horror one goes through once Janus-faced with functions wanting like this.
Thankfully, then (or ought to we are saying .then()) came guarantees. They offered a way additional organized various to callbacks and most of the community quickly captive on to victimization them instead.
Now, with the foremost recent addition of Async/Await, writing JavaScript code is getting ready to get even better!
What is Async/Await?
Async/Await could be a long anticipated JavaScript feature that produces operating with asynchronous functions rather more pleasurable and easier to grasp. It devolves on high of guarantees and is compatible with all existing Promise-based genus Apis.  The name comes from async and await - the two keywords that will help us clean up our asynchronous code:
Async - declares an asynchronous function(async function someName(){...}).
Automatically transforms a regular function into a Promise.
When called async functions resolve with whatever is returned in their body.
Async functions enable the use of await.
Await - pauses the execution of async functions.(var result = await someAsyncCall();).
When placed in front of a Promise call, await forces the rest of the code to wait until that Promise finishes and returns a result.
Await works only with Promises, it does not work with callbacks.
Await can only be used inside async functions.
Here could be a straightforward example that may hopefully clear things up: Let's say we wish to urge some JSON file from our server. We’ll write a function that uses the axios library and sends a hypertext transfer protocol GET.
We’ve to attend for the server to retort, thus naturally this hypertext transfer protocol request are going to be asynchronous. Below we are able to see an equivalent operate enforced double. Initial with guarantees, then a second time mistreatment Async/Await.
// Promise approach function getJSON(){  // To make the function blocking we manually create a Promise.   return new Promise( function(resolve) {   axios.get('https://tutorialzine.com/misc/files/example.json')        .then( function(json) {               // The data from the request is available in a .then block      // We return the result using resolve.        resolve(json);           });  });   }    // Async/Await approach    // The async keyword will automatically create a new Promise and return it. async function getJSONAsync(){     // The await keyword saves us from having to write a .then() block.   let json = await axios.get('https://tutorialzine.com/misc/files/example.json');    // The result of the GET request is available in the json variable.  // We return it just like in a regular synchronous function.   return json;  }
It's pretty clear that the Async/Await version of the code is much shorter and easier to read. Other than the syntax used, both functions are completely identical - they both return Promises and resolve with the JSON response from axios. We can call our async function like this:
getJSONAsync().then( function(result) { // Do something with result. });
So, does Async/Await make promises obsolete?
No, not at all. once operating with Async/Await we tend to ar still victimisation guarantees beneath the hood. a decent understanding of guarantees can really assist you within the long-standing time and is very counseled.
There are even uses cases wherever Async/Await does not cut it and that we need to return to guarantees for facilitate. One such situation is after we ought to build multiple freelance asynchronous calls and look forward to all of them to end.
If we tend to attempt to try this with async and expect, the subsequent can happen:
async function getABC() { let A = await getValueA(); // getValueA takes 2 second to finish let B = await getValueB(); // getValueB takes 4 second to finish let C = await getValueC(); // getValueC takes 3 second to finish return A*B*C; }
Each wait decision can sit up for the previous one to come back a result. Since we have a tendency to do one go into a time the complete operate can take nine seconds from begin to complete (2+4+3).  This is not associate best answer, since the 3 variables A, B, and C are not addicted to one another. In alternative words we do not have to be compelled to grasp the worth of A before we have a tendency to get B. we are able to get them at a similar time and shave off a number of seconds of waiting. To send all requests at a similar time a Promise.all() is needed.This may ensure we have a tendency to still have all the results before continued, however the asynchronous calls are firing in parallel, not one when another.
async function getABC() { // Promise.all() allows us to send all requests at the same time. let results = await Promise.all([ getValueA, getValueB, getValueC ]); return results.reduce((total,value) => total * value); }
This way the operate can take a lot of less time. The getValueA and getValueC calls can have already finished by the time getValueB ends. rather than a total of the days, we'll effectively scale back the execution to the time of the slowest request (getValueB - four seconds).This way the function will take much less time.
Handling Errors in Async/Await
Another great thing about Async/Await is that it allows us to catch any unexpected errors in a good old try/catch block. We just need to wrap our await calls like this:
async function doSomethingAsync(){ try { // This async call may fail. let result = await someAsyncCall(); } catch(error) { // If it does we will catch the error here. } }
The catch clause can handle errors provoked by the anticipated asynchronous calls or the other failing code we tend to might have written within the attempt block. If the situation requires it, we can also catch errors upon executing the async function. Since all async functions return Promises we can simply include a .catch() event handler when calling them.
// Async function without a try/catch block. async function doSomethingAsync(){ // This async call may fail. let result = await someAsyncCall(); return result; } // We catch the error upon calling the function. doSomethingAsync(). .then(successHandler) .catch(errorHandler);
It's important to choose which method of error handling you prefer and stick to it. Using both try/catch and .catch() at the same time will most probably lead to problems.
Browser Support Async/Await is already on the market in most major browsers. This excludes solely IE11 - all different vendors can acknowledge your async/await code while not the requirement of external libraries.
Node developers may get pleasure from the improved async flow as long as they're on Node eight or newer. It ought to become LTS later this year.
If this compatibility does not satisfy you, there are many JS transpilers like Babel and matter, and also the Node.js library asyncawait that provide their own cross-platform versions of the feature.
Conclusion
With the addition of Async/Await the JavaScript language takes a large breakthrough in terms of code readability and easy use. the flexibility to put in writing asynchronous code that resembles regular synchronous functions are appreciated by each beginners to JavaScript and veteran coders.
Async on MDN
Await on MDN
Async/Await: The Hero JavaScript Deserved
Where Did Async/Await Come from and Why Use It?
We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs. As a reputed Software Solutions Developer we have expertise in providing dedicated remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to
get in touch with us!
0 notes
t-baba · 4 years ago
Photo
Tumblr media
A way to look up JavaScript operators
#514 — November 13, 2020
Unsubscribe  |  Read on the Web
JavaScript Weekly
Tumblr media
10 Insights From Adopting TypeScript At Scale — A fantastic writeup (from a TC39 member, no less) of how Bloomberg (the financial media company) adopted TypeScript and now has 2,000 full-time JavaScript engineers. Curiously we also learn that Bloomberg also have their own JavaScript runtime built around the V8 engine.
Rob Palmer (TC39 and Bloomberg)
A Way to Look Up JavaScript Operators — Quick, name as many operators as you can! Got to about ten or so? This site covers about fifty with a quick explanation of each (well, except the bitwise ones).
Josh W Comeau
The Most Complete Spreadsheet Solution for JavaScript Apps — New Release: Fast enterprise JavaScript spreadsheet for delivering true spreadsheet experiences. Learn more about SpreadJS v14 including native Excel I/O, Calc Engine with 450+ functions and more. Download a free trial or view the online demos.
SpreadJS by GrapeCity, Inc. sponsor
Angular 11 Released — Are you one of the allegedly 1.7 million developers using Angular? Maybe experimental webpack 5 support, faster builds, improved hot module replacement support, and automatic inlining of fonts can tempt you onto the latest version.
Mark Techson (Google)
Babylon.js 4.2 Released: Powerful 3D Rendering Engine — Babylon.js is a particularly powerful 3D rendering engine aimed at artists, game developers, and anyone with 3D ideas to explore. New to 4.2 is a new particle editor, sprite editor, texture inspector, and more. See the playground if you want a quick play.
Babylon.js
'No More Free Work from Marak' — The creator of faker.js (a library for creating dummy data) pushing back against supporting businesses for free with his open source work has become a cause célèbre in the past week. “Pay me or fork this,” he says. Whatever your take, the topic of work vs reward in open source will remain both important and divisive.
Marak X
⚡️ Quick bytes:
We've not had time to go through them yet, but VueConf Toronto has released a lot of talk videos from their recent online conference.
Replay is a React-inspired JavaScript game engine and they're having a game jam starting today and running for a week.
Windows user? The Windows Terminal Preview 1.5 release may interest you.
The TypeScript team have written up some notes on TypeScript's release process.
📚 Tutorials, Opinions and Stories
Rethinking the JavaScript Pipeline Operator — Dan concludes “I hope that TC39 decides to reject this proposal” but it’s interesting to see how he reaches that conclusion.
Dan Shappir
Understanding Modules and import and export Statements — Modular programming demands, well, modules, and JavaScript now has built-in support for these and here’s the basics of their operation.
Tania Rascia
Is Your JavaScript Testing Stack Holding You Back? — Learn how to boost your productivity with the ultimate development workflow.
Wallaby.js sponsor
Things I Don’t Like About Vue.js (as a React Engineer) — Well, we love Vue, but to be fair to Harry, he did write What Vue.js Does Better Than React recently too ;-)
Harry Wolff
Back to Basics: Event Delegation — Events don’t just occur on the element you apply them to. Instead they go all the way down the DOM tree to the event and back up again. Christian demonstrates where this can help you out.
Christian Heilmann
How to Detect When a Sticky Element Gets Pinned — …thanks to the IntersectionObserver API.
David Walsh
Live Workshop: Getting Started with OpenTelemetry in Node.js
Lightstep sponsor
▶  How to Recreate Tic Tac Toe with HTML, CSS, and JavaScript James Q Quick
You're Probably Not Using Promise.All Enough Sam Jarman
How to Create a Commenting Engine with Next.js and Sanity Bryan Robinson
▶  My VS Code Setup: Must Have Configurations and Shortcuts James Q Quick
🛠 Code & Tools
Tumblr media
Mermaid: Markdown-'ish' Syntax for Generating Flowcharts, Sequence Diagrams, and More — Being able to ‘draw’ diagrams in a structured, text-based and have them render into something presentable is pretty appealing.
Knut Sveidqvist
jsdiff: A JavaScript Text Diffing Implementation — Can compare strings for differences in various ways including creating patches for the changes. The library is quite mature but just reached version 5.0. There’s an online demo too.
Kevin Decker
core-js 3.7.0: A Modular Standard Library and Polyfills for JS — A popular collection of polyfills covering ECMAScript features up to ES2021 level. The project has had some interesting problems recently, but releases are now flowing again.
Denis Pushkarev
CodeFix - Automatically Clean Up Technical Debt
CodeFix sponsor
React Frontload 2.0: Simple Full-Stack Data Loading for React — Do full stack data loading and state management inline in React components by writing a data loader in your component (with a hook) and it ‘just works’ with SSR and in the browser.
David Nicholas Williams
Running Vue.js in a Web Worker? — A promising prototype of running Vue.js in a Web Worker so that work is offloaded to a background thread with updates being sent back to the main thread asynchronously.
Jerzy Głowacki
Dexie.js: A Minimalistic IndexedDB Wrapper — IndexedDB is a widely supported browser API for data storage and Dexie aims to make it simpler to use (and will offer an approach for server syncing too.)
David Fahlander
Microsoft Edge Tools for VS Code — Use the Microsoft Edge Tools from within VS Code to see your site’s runtime HTML structure, alter its layout, fix styling issues as well as see your site’s network requests.
Visual Studio Marketplace
ShareDB 1.5: Realtime Database Backend Based on Operational Transformation — For when you need real time synchronization of JSON documents (such as for behind a real time collaboration app).
ShareJS
💻 Jobs
Senior / Intermediate Full Stack Developers (Sydney or Brisbane) — A SaaS business with phenomenal growth. True flexible working. You’ll have 5+ years in JavaScript / TypeScript, as well as production experience with AWS/Serverless.
Compono
JavaScript Developer at X-Team (Remote) — Join the most energizing community for developers and work on projects for Riot Games, FOX, Sony, Coinbase, and more.
X-Team
Find Your Next Job Through Vettery — Create a profile on Vettery to connect with hiring managers at startups and Fortune 500 companies. It's free for job-seekers.
Vettery
👀 A Correction
The File System Access API: Simplifying Access to Local Files — Several issues ago we mistakenly referred to this API’s spec as an ‘open standard’ when it's just a spec. It's Chrome only (for now), not a W3C standard, though it remains an interesting idea. (Thanks to reader Šime Vidas for noting our mistake and noting that the path from the WICG to a W3C standard is a long one indeed!)
Pete LePage and Thomas Steiner
by via JavaScript Weekly https://ift.tt/2IzXSPs
0 notes
tak4hir0 · 5 years ago
Link
JS完全に理解した……(し て ま せ ん)  見出しはエンジニア界隈でお馴染みのダニング=クルーガー曲線のアレでございます。2020年6月に出たばかりの最新のJS本を読んだので書評です。  570ページ余りの分厚さで電子版もあり。著者はECMAScriptの仕様にも関わっているazuさん、Angular日本ユーザー会代表のSuguru Inatomiさんと強力な布陣。ES2015(ES6)以降も進化を続けるJavaScriptについて、完全にES6をベースにしたモダンな入門書となっています。  コンテンツはGitHubで管理されてオープンソースとして執筆され、様々な人がコントリビュートした結果が反映される面白い作り方になっています。Web版もすべて無料で参照できるのですが、こういう体系的な情報はまとまった本で学ぶことにしているので電子版で読みました。  僕も2017-2018年ごろに掛けてJS&フロントエンド技術には再入門して、あれこれ本を読んだり3つの有力フレームワークを学んだり比較した結果を【JavaScript】3大フレームワーク Angular, React, Vue.jsを比べてみよう (2018年4月) - Rのつく財団入り口の記事にしたらなんか沢山アクセスがあったり、実案件でも実戦投入してきました。 規模の大きい開発にNode.jsビルドシステムを導入してリファクタしたり、用が足りると判断した案件では伝統のjQueryを使ったり、最近は見た目重視の案件にVue.jsを投入したりしています。社内の周囲ではJSもできるマンという感じになっています。  では(本来の意味で)JSを完全に理解しているか……というとけっこう怪しくて、使ってない構文もあればまだまだ理解しきれていないところもあります。またエンプラ世界の辛みで2020年の今もIE11の亡霊がなかなか絶滅してくれず、泣く泣くIE11でも動く古い書き方で留めておいたりすることもあります。(まあBabelとかもありますが。)  最近のフロントエンド人気にあやかってググっても大量に出てくるJavaScript情報でも、うっかり油断すると変数宣言が未だにvarだったり、古い情報や既に正しくなくなっている情報も出てきます。まとまった信頼できる情報を手元に置いておきたいなあとはよく思っていました。  『改訂新版JavaScript本格入門』という良本があるのですが、物理本を会社に残したままテレワークに突入してしまったので、これを機に改めて読んでみることにしました。 第1部 基本文法 constは再代入できないけどオブジェクトだと中のプロパティは変えられるので厳密には定数ではない、nullとundefined の比較……などやっぱり頭から抜けてた情報がありました。デバッグ方法やエラーの種類も書いてあるのがいいですね。 第7章 暗黙的な型変換 ここを読んでこれからは厳密等価演算子の === を常に使おうと固く決意して、今のプロジェクトのコードにも適用しました。(笑) falsyになる6種類の分類も雰囲気でやってたので明示的な解説がありがたいです。 第8章 関数と宣言、第9章 文と式 8章はよく忘れがちなアロー関数の話、9章は文と式は別で文はセミコロン必要という話。 全体的に本書はコード例も簡潔で良いですね。そしてつくづくJavaScriptの初期仕様はバグを出しやすい曖昧さがあちこちにあったんだなあと思います。 第10章 条件分岐 If文の中に変数を書くとfalsyかどうかで判定する。ということは「文字列がundefinedでもnullでも空文字でもない」を判定する時は if (varName) {....}だけでいいのか...! ネタ画像ですいません 第11章 ループと反復処理 配列の forEach, filter, someの後はコールバック関数であれば良いのだから、アロー関数にしなければもしやES2015以前のIE11用コードでも使えるのかな...? などなど、曖昧に使っていたところにけっこう知識の抜けがありそました。 第12��� オブジェクト JSでよく出てくるオブジェクトのおさらい。厳密にはキーと値の組のことをまとめて「プロパティ」と呼ぶのは地味に知らなかった...! キーの存在確認はundefinedとの比較より、in演算子かhasOwnPropertyメソッドの方が安全なんですね。 Object.keys以外にもES2017で列挙メソッドが増えたり、進化が続いているなあという印象です。 第13章 プロトタイプオブジェクト 普段目にしないのでよく忘れる、Object.prototypeというプロパティにオブジェクトが入っており組み込みオブジェクトはみんなこれを継承しているから組み込み関数が使えるよという話。例が簡潔かつ豊富で判りやすいです。 第14章 配列 よく出てくる配列の話。配列もオブジェクトの一種だけどArray.isArrayは配列かどうかだけを判定してくれるんですねえ。 findIndex, find, includesなどES2015以降の便利メソッドも増えているので、意識して新しい方を使っていかなければと思いました。IE11さえ、IE11さえいなければ...(呪呪呪呪呪) 列挙されると分かる、filterやreduceなどコールバック関数が必要な高階関数群。Array-likeなオブジェクトもあったりしてややこしい。破壊的メソッドと非破壊適用メソッドも名前から区別できれば良いのですが、そうもいかないですね。 第15章 文字列 頻出の文字列操作のあたり。sliceメソッドとsubstringメソッドの挙動が微妙に違うなど、なんでこういう言語仕様にしたんだろうなあと思います。JSにはいままでString#srartWithがなかったなど細かな発見もありました。 正規表現は普段はリテラルから、変数を使う場合はRegRxpクラスのコンストラクタから使うとGood。 match, exec, testと動作が少しづつ違う。コードの意図を判りやすくするにはStringクラスのメソッド群、柔軟な操作には正規表現を。 あまり使わないので曖昧になってた正規表現周りが整理できました。タグつきテンプレート関数は普段使わないのであまり理解できず……。 文字列の内部処理。絵文字も入ってくると文字コードの世界は奥が深い...! 第17章 ラッパーオブジェクト プリミティブ型の値にも裏で自動的に変換が掛かるので文字列からStringクラスのメソッドが呼べるんだよ、という話。JSでは常にリテラルを使うのがお作法。JSは「すべてがオブジェクトのように見える」言語だという話は納得です。 第18章 関数とスコープ 外側のスコープを順に見ていくのを「スコープチェーン」と呼ぶのは改めて知りました。 そしてJS特有の巻き上げの話。varによる変数宣言は宣言だけがより外側の関数かグローバルスコープに移動するので、この不思議な動きをするんですね。つくづくES2015までの世界のインターネッツのwebサイト群はよくこんな仕様の言語で壊れずに動いてたなと思います。 そして関数が状態をもったように振る舞ってくれるクロージャーの理解のカギは、JSの静的スコープとメモリ管理の仕組みである。この辺も難しいのですが、サンプルが明確なのでなるほど...!となります。 第19章 関数とthis JSでよくハマるthisの挙動の話がしっかり解決してあります。 普通に関数宣言したらundefined 、オブジェクトの中のメソッドから呼ぶとベースオブジェクトになる。 実はcall, apply, bindという明示的にthisを指定できる関数があるのは完全に忘れていました。 そしてよく問題になる、コールバック関数の中でthisを使う話。対処法は組み込み関数に引数として渡せるなら渡す、一時変数へ代入しておくというのはよく実際の開発時もやりますね。 そしてES2015以降のオススメが出��したアロー関数で、常に外側の関数のthis を指すから分かりやすい...というもの。例をもとに明確に書いていてありがたいです。ES2015の仕様を策定した偉い人も通常の関数ではthisを使うべきではないと述べているそうで、このへんJSは難儀な言語だなぁと改めて思います。 第20章 クラス JSでも遂に書けるようになったクラス構文やsetter, getter。staticメソッドも書けるというはよく知りませんでした。 そしてclass 構文で書いたプロトタイプメソッドより、個々のインスタンスのコンストラクタに書いたインスタンスメソッドの方が優先されるというあたりもJS独特です。 そしてこれも独特なプロトタイプオブジェクトの話へ。インスタンスからクラスで定義したメソッドを呼べるのは、内部的にprototypeへの参照を持っているから。なるほどChromeの開発者ツールで見ると時々出てくる __proto__ はこの辺と関係しているんですね。 第21章 例外処理 Errorオブジェクトの種類などが明確に説明されています。 第22章 非同期処理: コールバック /Promise/Async Function JSでは非同期処理は「並行処理」、メインスレッドの中で切り替えながら行われる。名前はよく聞くWeb Worker APIの完全な非同期処理は「並列処理」で両者は違うもの。このへん日本語が混乱しがちです。 非同期処理では例外をキャッチできないのは実は知りませんでした。 そして今までのJSでコールバック関数の第1,2引数に渡るものでエラーを判別していたものは「エラーファーストコールバックスタイル」とちゃんと名前がついていました。 そして非同期処理をより簡単に表現しよう...と導入されたPromiseの話。予め成功時、失敗時の動きを関数で定義して引数で渡して実行することができます。メソッドチェーンは本書ではPromiseチェーンと呼んで三重、四重の処理をしたり。 本書の例は全体的に分かりやすいのですが、構文に慣れていないせいかPromise周りは難しく感じました。 非同期処理すべてが終わったら先に行く Promise.all, 一番最初に終わった処理だけ採用のPromise.race, そしてES2017から使えるようになる、より簡潔に書けるようになる async function 。 難しいですがこのへんは極めると色々応用が効きそうです。Promiseについてだけ別の本をPDFで作ったそうですが、確かに奥がかなり深そうです。 第23章 Map/Set JSにありそうで今までなかったMapとSet。オブジェクトを使う場合との比較など。使い方は他の言語とほぼ同じです。 JSON.stringifyに第2引数以降があるのはよく知りませんでした。 第25章 Date 言語仕様の分だけだと足りないところもあるDate周り。なるほど機能不足を補うために時々聞くライブラリのmoment.jsなどが出てくるのですね。 第1部の終わりにはモジュール機能の話、そしてJSの仕様が2015年以降毎年新しくなって進化している話が述べられています。 世の中の情報が膨大で間違っていることもあるので、適切な調べ方をもっておくことが大切...というのはなるほどなと思います。次の第2部は3つのユースケースを題材にした実際の開発での実践編���す。 第29章 アプリケーション開発の準備〜第30章 ユースケース: Ajax通信 Node.jsを入れたりよくやる準備をしていざ開発へ。 最終的にはローカルで立てたサーバーで画面に入力したidを元に、GitHubのAPIと通信してユーザー情報を取得して表示する画面を作っていきます。最初はサンプルコードがイベントの中に長い処理がすっぽり入ってかなり不格好ですが、どんどんリファクタリングされて分割され綺麗に整っていきます。 通信はES6以降のFetch APIを使っていて、ここもついjQueryのメソッドを使っちゃったりするので従来のやり方から切り替えないとなと思いました。 そしてPromiseを使って実装すると、前の処理の結果をラップして次の処理に渡していけるんですね。さらにasync functionを使って書くとサーバーサイドの言語の順次処理のように簡潔に書けます。同期処理と非同期処理が両方あっても連鎖できるのがポイントですね。このへん実際使って慣れていかないとなあと思いました。 第31章 ユースケース: Node.jsでCLIアプリケーション 拡張子.mdのファイルを読み込んでHTMLを出力するコンソールアプリケーションを作っていきます。追加するライブラリはcommander, markedなど。オプションをデフォルト設定して起動時の指定を有線する所などは他の言語と同じ感じ。この章の例は分かりやすいですね。 外部ファイルの読み込みはES moduleの標準でなくCommonJSモジュールを使っていて一般的にはどっちが多いのだろうと思いました。 第32章 ユースケース: Todoアプリケーション JSの例でよく出てくるToDoアプリを開発します。最初は画面をそのまま実装し、DOM要素に直接値を持たせると限界があり、またどんどんイベントを登録していくと複雑になる一方である……と従来のやり方の問題点を提示します。 その後は状態やデータを別に持つModelクラスに分離するやり方を導入します。 さらにフロントエンドでよくあるObserverの考え方を導入、EventEmitterクラスを作ります。これも分かると何のことはなくてイベント名、コールバック関数の組で処理を貯めてSetに保持、外側からイベント発生時に emit されたら貯めてある中からコールバック関数を取り出して発動させるだけなんですね。これがModelクラスの親になるのが肝か。 最終的にはHTMLを描画する部分もViewクラスに切り出して、MVVMアーキテクチャ的なクラス構成になります。なんとなく思想的にはJSフレームワークのVue.jsに近い感じがしました。ViewクラスでDOM要素を描画しているところはReactっぽくもあります。メイン処理のAppクラスが役割的にはViewModelに近いような形でしょうか。 最終的にはリファクタリングして綺麗になるのですが、ピュアJSのみ(=いわゆるバニラJS)で書くと、それでもコード全体は結構な量になります。これをより短く書けるJSフレームワークやライブラリが生まれる訳だなあと思いました。 まとめ:JS完全に理解した……の先へ行ける、モダンJSのまとまった最新情報が得られる本!  と読書メモを並べてみましたが、自分的には案の定というべきか、忘れているところ、理解があやふやなところがあちこちにありました(汗)。よい補完になりました。特に難しいと思ったのはやはりPromise周りでした。改めて理解を深めないと……。  複数の方が関わってコントリビュートしていることもあり、日本語の文章は読みやすいです。このへんは翻訳本に比べると強みですね。また全体的にコード例が豊富かつ簡潔で、(難しいところは難しいのですが)理解しやすいと思います。他の難しそうな本で挫折したという方も本書ならリベンジできるのではと思います。  本書のTwitterハッシュタグ #jsprimer を概観していると多くの人が呟いているのが、「今まで雰囲気でやっていた/理解していたところがよく分かった」というもの。僕も同じような感想を持ちました。変化を続けるJavaScriptについてまとまった、かつ今後もアップデートが期待できる情報源として、学習の傍らや実際の開発の傍らで大いに役立つことでしょう。 JS完全に理解した……の先へ! JS完全に理解した……の先へ行けるリンク集 本と同じ内容のWeb版。最後の『付録:JavaScriptチートシート』が解説ページそれぞれに飛べてとても便利です。 jsprimer.net 本書の続編の位置付けに『JavaScript Promiseの本』も無料公開されています。Promiseだけで一冊本ができるのが凄い……! それぐらいPrromise周りは難しく奥が深いということですね。 azu.github.io コンテンツ自体がオープンソースとして管理された本書のGitHubリポジトリ。 github.com 達人出版会からも出版されています。 tatsu-zine.com はてブ300の大注目を浴びた、なぜ書かれたかの記事。 efcl.info Web版を読んでJSに再入門した方の記事。 pagain.hatenablog.com Web版を読んだQiitaの感想記事。 qiita.com 本書でArrow Functionが分かった方の記事。 www.ry0takahash1.com 本書で学習を始めた方の記事。 自分用メモ JavaScriptの勉強を始めた #jsprimer - Mitsuyuki.Shiiba 500はてブと注目された、Ruby界隈やQiitaでお馴染みの伊藤淳一さんの感想記事。タイトルに埋め込まれたギャグにもっとツッコミを入れて欲しかったそうであります。 『「すでに他の言語のプログラミング経験はあるし、JSもある程度触れるが、ES2015以降の機能は雰囲気でしか理解していない」という人間にはピッタリの一冊でした』という感想に納得です。 blog.jnito.com JS完全に理解した……の先に行ける、モダンなJSが学べる最近の本 本書の作者さんによる、レベル別のJS本のおすすめリスト。JS本も列挙すると色々あるのですが、2010年代後半~の新しい本があまりないんですよね。 JavaScriptのレベル別書籍のまとめ · GitHub 『改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで』が初版2016年。2019年10月に6版でES2015の情報も強化され、電子版にも��新が入っています。 技術書では安心の山田 祥寛さんの本。評判も良く、言語経験があってJS再入門したい方には今もお勧めです。僕がJS再入門したのもこの本です。リファレンス用に会社の机に1冊置いてあるのですが、今ごろ埃をかぶってるだろうか…… Amazonでベストセラーになっている『確かな力が身につくJavaScript「超」入門』は2019年9月の最新。前述の本よりややランクを落とし、より初心者向け。開発経験のない方、浅い方はまずはここからしっかりやるのも良いと思います。  約束のオライリー本ですと、電子版がないですが『初めてのJavaScript 第3版 ―ES2015以降の最新ウェブ開発』のが2017年1月刊行でぎりぎり最近といえるでしょうか。450ページあります。前述のレベル別リストだとこれも初心者向けの分類となっています。  「サイ本」として有名な『JavaScript 第6版』はさらに鈍器力の高い800ページ越え、こちらは2012年刊行で古めです。この2冊は表紙デザインがやや似ているので注意です。(「初めての~」の表紙はカバさん?) コードサンプルが大量に載ったスタイルの本ですと、『JavaScript コードレシピ集』が2019年1月、『JavaScript逆引きレシ�� 第2版』が2018年10月。
0 notes
kimzer · 7 years ago
Text
好用的 Promise (bluebird) 與要注意的地方
背景
不是說,應該都可以用 async / await 方式作為新一代 js 操作的方式嗎,那跟 Promise 有什麼關係,反正全都 async / await 就好啦。不過,故事其實不是這麼簡單的,畢竟 async / await 其實是對 Promise 的封裝。而且,也不是大家的開發環境都是完全支援 async / await 的。所以,多多了解 Promise 還是非常重要的。
說到 js 的 Promise 大概就不得不提到 bluebird 吧,畢竟, bluebird 也算是 Promise 的完整整合方案了,也就是差不多都使用 bluebird 來取代原始的 Promise 所以,就來聊聊 bluebird 吧
設定
這部分也不多說了,反正基本上,我都會直接設定為:
const Promise = require('bluebird') global.Promise = Promise
也就是說,直接用 bluebird 取代原生的 Promise ,或是說,對於舊版本來說,就是讓它直接支援 Promise 吧,之後就不用管了
注意
其實主要是要說明要注意的地方,大部分來說,都是在考慮使用 .all, .props, .map, .each, .mapSeries, .filter, .reduce, .any, .some, .race
其實可以分幾個部分來說明
.all, .props
先說明這兩個部分:
先看例子:
Promise.all([ runPromise1(), runPromise2(), runPromise3() ]) .then(res => { console.info({ res }) }) Promise.props({ app1: runPromise1(), app2: runPromise2(), app3: runPromise3() }) .then(res => { console.info({ res }) })
相同:
兩者都是批次執行多個 Promise function
皆會執行所給定的所有 Promise function
回傳值 res 都是執行的多個 Promise 執行結果的集合
皆為並行執行,也就是說,執行多個 Promise function 時,無關先後順序,所以 不應該 作為有先後相依相關的 Promise function 處理
相異:
給予的 iterator 不同, .all 是給予一個 Array 而 .props 是 Object
最大的差別應該是產生的結果 res 格式不同,.all 是會產生 Array [] ,而 .props 則是產生 Object {}
使用建議:
如果只想要快點完成 Promise 相關的動作,而且也未必一定要考慮產生的結果,使用 .all 寫法會比較簡單方便點
如果要考慮產生的結果 res 的值,而且會運用在接下來的操作中,則建議使用 .props ,畢竟產生的結果是 Object {} 格式,可以參考使用相關的 key 作為接下來處理的對象,可以減少可能發生的對應問題與錯誤
兩者皆是 並行執行 多個 Promise function,所以仍要注意,如果一次執行太多的 Promise function ,或是太複雜的 Promise function 時,可能會有記憶體不足或是過高的 system load 問題。不過每種機器到底建議要限制多少個可並行執行的 Promise function,則可能應該因時因地作為考量
.each, .map, .mapSeries
先看例子:
Promise.resolve(items) .each(item => { console.info({ item }) return handler(item) }) .then(res => { console.info({ res }) }) const concurrency = 3 Promise.resolve(items) .map(item => { console.info({ item }) return handler(item) }, { concurrency }) .then(res => { console.info({ res }) }) Promise.resolve(items) .mapSeries(item => { console.info({ item }) return handler(item) }) .then(res => { console.info({ res }) })
相同:
傳入的項目 items 皆為 Array []
處理完成的項目 res 皆為 Array []
皆會在給定的 items Array 執行完成後,才會到 res 的結果
相異:
.each 與 .mapSeries 相似,皆會依順序處理 items 項目
.map 和 .mapSeries 產生的結果 res 皆是回傳 .map, .mapSeries 處理後的資料,而 .each 產生 res 則是原始給 .each 處理的 items 資料
.map 可以多加一個 concurrency 參數,可以確保在執行 .map 時,同時並行處理的項目,當完成後,才處理接下來給定的 items 項目,直至所有給定的 items 處理完畢
使用建議:
除非在特定情況,必須要使用給定的值 (如,只是提供其他處理,並不考慮 .each 處理) 否則都 不 應該使用 .each
如果要增加執行速度,建議使用 .map ,但是為了要確保系統穩定性,建議使用 concurrency 參數的設定
如果非常確定要確保 順序 (如:排序相關),則應該使用 .mapSeries
.map, .filter, .reduce
例子:
const concurrency = 3 const initialNumber = 0 /** * map * / Promise.resolve(items) .map(item => { console.info(item) return handler(item) }, { concurrency }) .then(res => { console.info(res) }) /** * filter * / Promise.resolve(items) .filter(item => { if (checkCondition(item)) { return handler(item) } }, { concurrency }) .then(res => { console.info(res) }) /** * reduce * / Promise.resolve(items) .reduce(item => { return handler(item) }, initialNumber) .then(total => { console.info(total) })
相同:
皆是傳入 Array
操作概念與原生 [].map,[].filter 與 [].reduce 概念相似
.map 與 .filter 皆有 concurrency 設定可以提供
相異:
.map 輸入時有多少個 Array item,則亦是回傳 Array 相同 item 數目
.filter 輸入時有多少個 Array item,根據處理後,回傳的 Array item 數目可能會比較少或是為空 Array
.reduce 輸入時有多少 Array item,根據處理後,以及給定的 initialNumber 相加後的處理總數,如果沒有提供 initalNumber,則會回傳 undefined
.map 與 .reduce 基本上在標準 js 的使用來說,reduce 功能會比較強大,但是,在 Promise (bluebird) 中,則是完全不一樣的操作概念
使用建議:
.filter 處理 Array 來說,更適合與可能輸入的 Array element 數目與輸出數目不相同情形 (如:部分使用 .map 操作時,不需要的資料會變成 undefined,而 .filter 則沒有此一問題)
.reduce·更適合使用於單純計算綜合,如果沒有設定 initialNumber 時,則沒有任何有意義的回傳值
.all,.some,.any,.race
例子:
Promise.all([ runPromise1(), runPromise2(), runPromise3(), runPromise4() ]) .then(res => { console.info({ res }) }) const count = 2 Promise.some([ runPromise1(), runPromise2(), runPromise3(), runPromise4() ], count) .then(res => { console.info(res) }) .catch(Promise.AggregateError, (err) => { err.forEach(error => { console.error(error) }) }) Promise.any([ runPromise1(), runPromise2(), runPromise3(), runPromise4() ]) .then(res => { console.info(res) }) Promise.race([ runPromise1(), runPromise2(), runPromise3(), runPromise4() ], count) .then(res => { console.info(res) })
相同:
皆是傳入多個 (Array) 的 Promise / Iterable 項目
相異:
.all 會執行所有給定的 Promise / Iterable 項目,而且,所有項目必須是執行成功的,並且,回傳值也是 Array 的格式
.some 必須制定 count 的數值, count 數值必須代表最先完成 (無論成果或失敗 - resolve / reject) 的 Promise / Iterable 項目,回傳值為 Array ,長度應該與給定的 count 長度相同
如果想要擷取失敗 (不是過慢) 的項目,則可以使用 Promise.AggregateError 將所有的錯誤訊息整合、輸出
.any 類似於使用 .some 方式,而 count = 1 的概念,而且回傳資料為單一項目,而不是 .some 的 Array 格式
.race 與 .any 或是 .some 相似,但是, .race 只會擷取最快成功完成的一筆資料,作為回傳值
使用建議:
如果想要取得最早成功完成的項目,則應該考慮 .race 方式
如果只要取得最先完成的項目,無論成功與否,則可以考慮使用 .any 的方式
如果期望有些功能是成功,有些失敗,而且有設定最小必須成功的限制筆數,則應該使用 .some 方式
如果要確定每一個 Iterable 都必須成功,則應該使用 .all 或是 .props 方式
8 notes · View notes
Text
WebサイトをPWA(プログレッシブウェブアプリ)にする手順とその必要性
Tumblr media
ここ数年、PWA(プログレッシブウェブアプリ)が非常に注目されています。通常のWebページとスマホアプリそれぞれの利点を兼ね備えており、導入したサイトではコンバージョンやユーザーエクスペリエンスの改善が大きく見込めます。
WebサイトをPWAにする手順とその必要性を紹介します。
Turn Your Website into a PWA by Luca Spezzano
下記は各ポイントを意訳したものです。 ※当ブログでの翻訳記事は、元サイト様にライセンスを得て翻訳しています。
PWA(プログレッシブウェブアプリ)とは
プログレッシブウェブアプリ(Progressive Web Apps)とは、Googleも推奨する通常のWebページとモバイルアプリのハイブリッドです。PWAは最新のブラウザが提供する機能とスマホのエクスペリエンスの利点を兼ね備えており、HTML, CSS, JavaScriptなどの標準的なWebテクノロジーで構築されています。
機能としては、オフライン作業、プッシュ通知、デバイスのハードウェアアクセスなど、ネイティブアプリと同等のユーザーエクスペリエンスを可能にします。スマホアプリとまったく同じように、スマホのホームに追加することもできます。
なぜPWAを構築する必要があるのですか?
数週間前に私がPWAに関する詳細情報を探した時に、pwastats.comというとても素敵なサイトを見つけました。このサイトにはPWAを利用している有名企業のデータがあり、どのようにしてサイトのパフォーマンスを改善したのかがよく分かります。
プログレッシブウェブアプリを使用すると、ロード時間を短縮され、ユーザーがオフラインでナビゲートできるようにし、サイトで費やす時間を増やしたり、収益を増やしたり、スマホアプリよりもはるかに多くのことができます。
すでにPWAを採用しているのはどこですか?
Uber, Instagram, Twitter, Pinterest, Forbes, Alibaba
Twitter、Instagram、Uber、Pinterest、Forbes、Alibabaなど、世界の多くの企業でプログレッシブウェブアプリが採用されています。
PWAを作成する時に必要なもの
プログレッシブウェブアプリを作成するには、最初にレスポンシブ対応のWebサイトを作成する必要があります。その後に、Web App ManifestとService Workerの2つが必要です。これらがどのようなものか見てましょう。
Web App Manifest
Web App ManifestはシンプルなJSONファイル「manifest.json」で、ブラウザにWebアプリとユーザーの動作を伝えます。 プロパティは下記の通りです。
name: アプリのインストールプロンプトで使用される名前。
short_name: ユーザーのホーム画面、ランチャー、スペースが限られている他の場所で使用される名前。
start_url: 起動時にアプリを開始する場所をブラウザに指示します。
display: アプリの起動時に表示されるブラウザUIをカスタマイズできます。最も使用される値はstandaloneです。Webアプリを開き、スタンドアロンのネイティブアプリのように表示します。
background_color: アプリの起動時にスプラッシュ画面で使用されます。
theme_color: ツールバーの色を設定します。
orientation: 特定の方向を強制することができます。
scope: 私��通常このプロパティを使用しませんが、ブラウザがアプリ内にあると見なすURLのセットを定義し、ユーザーがアプリを離れたタイミングを決定するためによく使用されます。
icons: ユーザーがホーム画面にサイトを追加するときに、ブラウザが使用する一連の画像を定義できます。
Service Worker
これは基本的に、メインブラウザスレッドとは別に実行されるJavaScriptファイルで、Service Workerを使用して実行できます。
ネットワーク リクエストの傍受する。
キャッシュからリソースをキャッシュ・取得する。
プッシュメッセージを配信する。
Service Workerのライフサイクル
Registration: Service Workerの場所をブラウザに通知し、バックグラウンドでのインストールを開始する。
Installation: Service Workerのインストール時にいくつかのタスクを実行できるインストールイベントをトリガーする。
Activation: Service Workerによって制御されて開いているページがある場合、新しいService Workerは待機状態になります。新しいService Workerは、古いService Workerを使用しているページがロードされなくなった時にのみアクティブになり、一部のタスクの実行にも使用できます。
PWAを5分で構築しよう
では、プログレッシブウェブアプリを実装してみましょう。
実装の前にまずは、Lighthouseをインストールすることをお勧めします。
LighthouseはWebページの品質を向上させるためのツールで、下記のようなレポートを取得できます。
Lighthouseのレポート
このレポートからは、Webサイトやアプリのパフォーマンス、アクセシビリティ、ベストプラクティス、SEOおよびPWAを改善するために必要な問題を確認できます。
ファイル構造は、下記の通りです。
ファイル構造
Githubに完全なコードがあります。ブランチを切り替えて、動的キャッシュまたは静的キャッシュを表示できます。
index.htmlで、manifest.jsonを呼び出します。
<link rel="manifest" href="/manifest.json">
ただし、app.jsファイル(Service Workerを登録する場所)とPWAを最適化するために必要なメタタグも記述する必要があります。
<link rel="apple-touch-icon" href="/assets/images/logo-96x96.png">
<meta name="apple-mobile-web-app-status-bar" content="#FFE1C4">
<meta name="theme-color" content="#FFE1C4">
<script src="/assets/js/app.js"></script>
メインのタグはこれで終了です、もちろんさらに多くのタグがあり、異なるパスを使用することもできます。
静的キャッシュ
はじめに、静的キャッシュから実装します。キャッシュにするリソース、画像やCSSやJavaScriptなどすべてを正確に手動で指定します。
この方法は特に、Webサイトのすべてのリソースをダウンロードし、ページの最初のランディング時にそれらのファイルをキャッシュする場合に便利です。
manifest.jsonに記述します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{
  "name": "Name Website",
  "short_name": "NameWebsite",
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#F4F4F4",
  "theme_color": "#F4F4F4",
  "orientation": "portrait-primary",
  "icons": [
    {
      "src": "/assets/images/logo-72x72.png",
      "type": "image/png",
      "sizes": "72x72"
    },
    {
      "src": "/assets/images/logo-96x96.png",
      "type": "image/png",
      "sizes": "96x96"
    },
    {
      "src": "/assets/images/logo-128x128.png",
      "type": "image/png",
      "sizes": "128x128"
    },
    {
      "src": "/assets/images/logo-144x144.png",
      "type": "image/png",
      "sizes": "144x144"
    },
    {
      "src": "/assets/images/logo-152x152.png",
      "type": "image/png",
      "sizes": "152x152"
    },
    {
      "src": "/assets/images/logo-192x192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/assets/images/logo-384x384.png",
      "type": "image/png",
      "sizes": "384x384"
    },
    {
      "src": "/assets/images/logo-512x512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ]
}
ブラウザがService Workerを許可しているかどうかを確認し、許可している場合はService Workerをapp.jsに登録します。
if('serviceWorker' in navigator){
  navigator.serviceWorker.register('/sw.js')
    .then(reg => console.log('service worker registered'))
    .catch(err => console.log('service worker not registered', err));
}
次に、sw.jsにService Workerを記述します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const staticCacheName = 'site-static-v1';
const assets = [
  '/',
  '/index.html',
  '/assets/js/ui.js',
  '/assets/css/main.css',
  '/assets/images/background-home.jpg',
  'http://bit.ly/33UpeVZ',
];
// install event
self.addEventListener('install', evt => {
  evt.waitUntil(
    caches.open(staticCacheName).then((cache) => {
      console.log('caching shell assets');
      cache.addAll(assets);
    })
  );
});
// activate event
self.addEventListener('activate', evt => {
  evt.waitUntil(
    caches.keys().then(keys => {
      return Promise.all(keys
        .filter(key => key !== staticCacheName)
        .map(key => caches.delete(key))
      );
    })
  );
});
// fetch event
self.addEventListener('fetch', evt => {
  evt.respondWith(
    caches.match(evt.request).then(cacheRes => {
      return cacheRes || fetch(evt.request);
    })
  );
});
キャッシュに入れるすべてのリソースを配列に格納します。
Installイベント
キャッシュにすべての静的アセットを追加し、Chromeのコンソールで確認します。
キャッシュされているリソース
Activateイベント
キャッシュの名前を変更すると、複数のキャッシュが格納され、問題が発生する可能性があります。それを避けるために、古いものを削除する必要があります。この関数では、キー(キャッシュ名)をチェックし、同じキーが前のキーと異なる場合は、前のキーを削除します。これを行うと、常に最後のキャッシュのみが存在します。
Fetchイベント
ここでは、すでにキャッシュが存在するかどうかを確認します。キャッシュが存在する場合はリソースをダウンロードしませんが、キャッシュからリソースを取得してコンソールで再度確認できます。
Networkパネル
Service Workerファイルを変更する時は、キャッシュの名前を変更する必要があります。これによりService Workerを更新し、新しいキャッシュを作成できます。
動的キャッシュ
動的キャッシュはナビゲーション中にすべてのFetchリクエストを自動的にキャッシュするため、非常に強力です。ただし、このキャッシュはAPIで呼び出しがある時に使用すると、新しいデータが変更されても反映されないため、慎重に使用する必要があります。
動的キャッシュを使用するには、sw.jsファイルを変更する必要があります。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const dynamicCacheName = 'site-dynamic-v1';
// activate event
self.addEventListener('activate', evt => {
  evt.waitUntil(
    caches.keys().then(keys => {
      return Promise.all(keys
        .filter(key =>  key !== dynamicCacheName)
        .map(key => caches.delete(key))
      );
    })
  );
});
// fetch event
self.addEventListener('fetch', evt => {
  evt.respondWith(
    caches.match(evt.request).then(cacheRes => {
      return cacheRes || fetch(evt.request).then(fetchRes => {
        return caches.open(dynamicCacheName).then(cache => {
          cache.put(evt.request.url, fetchRes.clone());
          return fetchRes;
        })
      });
    })
  );
});
Activateイベント
ここでは、静的キャッシュと同じことをします。
Fetchイベント
Fetchイベントでは、すべてのFetchリクエストを自動的にキャッシュに入れます。
キャッシュとLighthouseの実行後に両方を試すと、Webサイトがプログレッシブウェブアプリであることが分かります。
PWA Lighthouse
静的キャッシュと動的キャッシュのコードは下記からダウンロードできます。
静的と動的のどちらを使用すべきですか?
その答えは、ニーズとプロジェクトによって異なります。API呼び出しがない場合は動的キャッシュを使用します。逆にAPI呼び出しがある場合は静的キャッシュに保存するリソースを自分で選択できます。
Googleによるプログレッシブウェブアプリの詳細については、下記をご覧ください。
0 notes
z3459079 · 6 years ago
Text
My Lightning Talk: DOS / DDOS
I will be making a presentation of DOS and DDOS with a live demo on my project.
Here I will cover the basics of what DOS and DDOS are.
Vanilla DOS
Denial of Service (DOS) refers to any attack that prevents a web service from providing its intended service to its users and hence it covers a broad range of different attacks. Most commonly DOS attacks aim to either overload the server with meaningless requests to prevent other users from using the service, or to cause the service to quit, which would have the same user impact.
Distributed is a variation on DOS (DDOS) and the difference being that the requests come from multiple places. It is harder to detect and prevent as well since simple blacklisting does not work.
RUDY attacks
RUDY stands for (R U Dead Yet). It's a variant of DOS where you send legitimate POST requests based on a form present in the website. It declares extremely long Content Length via the header, and just fills it with garbage. The server doesn't know this is all garbage and processes the request as normal, little does it know that it is being used up on processing garbage.
This is a "slow-roll" variant of DOS and is really interesting. I may include it in my SA via some form that you can RUDY on.
Logic
The url exposed for DOS was /api/v1/transactions. This endpoint is entirely unthrottled and will shut down the server from a simple barrage of HTTP requests.
Simple JS or bash will do.
const http = require('http') const p = [] for (let i = 0; i < 20000; i++) { console.log('Performing operation', i) p.push( new Promise((resolve, reject) => http.get( 'http://MY_IP:MY_PORT', withHandler(resolve, reject) ) ) .then(() => console.log('Done')) ) } Promise.all(p) `
Then we can watch my local machine get a bit hot and bothered. After which it will stop serving my website!
0 notes
Text
how to stop puppy barking | train puppy to walk on leash
New Post has been published on https://dogtraining.dknol.com/english/how-to-stop-puppy-barking-train-puppy-to-walk-on-leash/?utm_source=Tumblr&utm_medium=Tumblr+%230+Freda+K+Pless&utm_campaign=SNAP%2Bfrom%2BBest+Dog+Training
how to stop puppy barking | train puppy to walk on leash
Tumblr media
The Weimaraner will inspect incoming artwork for beetles, moths and other critters that can damage museum collections And Now House Training is So Much Easier Just make a spreadsheet in excel and print it out, or simply buy some lined paper. ordering & shipping Free Info If your dog suddenly begins having “accidents” or if you have been unsuccessful at housetraining, contact a veterinarian right away. Resolving health issues may resolve the problem. Taking objects away from your puppy when they are in the middle of enjoying them only teaches them to guard these objects, not to give them up. Racine Campus Finance Take your puppy outside to potty before putting him in the crate. Bought chew toys to occupy your puppy in the crate? Charity 11 Ways You’re Shortening Your Dog’s Life Look over how long after eating they pooped u “We deal with the worst of the worst, and that’s what people don’t realize,” she said. “We deal with the dogs who, literally, their lives are on the line. And every one of us here cares so much, we don’t want dogs to die.” ©1997-2016 XO Group Inc. MAKE A DONATION Leash How to Potty Train a Puppy the Easy Way Open Cases JW Pet Patch welcomes contributions and comments from our users. We strive for civil, enlightened discussions on Patch stories and local issues. Please abide by our posting standards: Doreen Tovey Supplies Aggression (when off leash) Literature & Language Club Nylabone Last Name Reward your puppy every time they eliminate outdoors. Praise or give treats—but remember to do so immediately after they’ve finished, not after they come back inside. This step is vital, because rewarding your dog for going outdoors is the only way to teach what’s expected of them. Before rewarding, be sure they’re finished. Puppies are easily distracted and if you praise too soon, they may forget to finish until they’re back in the house. Eventually, work toward giving a tasty reward less frequently but with unexpected bonus treats—several at once, for example, for a particularly long “sit-stay.” Even young pups learn to appreciate the bonus concept of higher value rewards for better performance. I am intersted in (please check all that apply): You cannot successfully house train a puppy who is ill because their bodily functions will be too unpredictable. But of course if they’re ill, you want to have them back to good health anyway! We have 2 Italian Greyhounds (12 weeks old). Instead of crate training, we have a closed in terrace that is their “crate area”. We have built them a large grass box for potty, but they don’t use it a lot. I’m home with them most of the time, so I am able to correct their mistakes, but night time or if we are out of the house, they don’t use it. What would be the best way to get them going in the correct spot at the times they aren’t being supervised? Lucky Dog Kentucky Derby Canine Dimensions. 2018. All Rights Reserved. Sitemap. Privacy Policy. Video title Related services WA Startup Uses Trash To Make Prosthetics Whether you are a complete newcomer to dog training or have some experience, this course provides a comprehensive foundation of knowledge and skill. It is also a wonderful course for someone looking to change careers or looking to add training skill to his/her animal care skill set, such as a veterinary technician, pet sitter/walker, or groomer. Don’t punish your dog if they pee inside. Regardless of all those old training ideas punishment isn’t a good deterrent for house training. Yelling at your dog after the fact just confuses them and makes them nervous around you. If you catch your did in the act you can try to get their attention & move them outdoors. If you’re successful & they continue going once you get outside praise them like crazy. Holidays and HAWS Use “NO” for actions that are not appropriate. “NO” is an authoritative sound that should result in an immediate reaction. Do not use the word “NO” combined with your pup’s name. Dog Coat Types See How We Help Dogs & Veterans Considerations For An Indoor Bathroom Spot Ads and Cookies Obedience Training Intermediate Agility First of all, be picky when you choose your breeder. It starts with them and the habits they give your puppy when raising them. So check them out, visit the puppies at home with the breeder, ask for habits and observe their behavior. Although house training a puppy can be hard work and tiring – be patient and consistent, and all your efforts should pay off! Tricks: Wave, Take a Bow, Spin, Heel PureBites “Another word for training is teaching, so recognize that your new pet is looking for your guidance and praise,” she said. Your job this first week is to build up your bank account of trust with your puppy. Select by health condition Fruits & Berries (1) My mission is to help you have a wonderful relationship with your dog. Learn how to teach good manners, to decode canine behaviors, and have a really great time. For Clickertraining.com November 20, 2017 Life Jackets & Swim Suits Share this article: Toilet training a puppy 7. So much more! Manhattan, NYC, Chelsea, upper east side, uptown, downtown, midtown, East Side, West Side, Central Park, Washington Square Dog Park, Tompkins Square Park, SoHo, NoHO, Battery Park, Greenwich Village, TriBeCa (function()).call(this)}).call(n,t("../../../lib/node_modules/webpack/node_modules/process/browser.js"),t("../../../lib/node_modules/webpack/buildin/global.js"))},"./shared/polyfills/function.js":function(e,n)Function.prototype.bind,"./shared/polyfills/object.js":function(e,n)Object.keys,"./shared/polyfills/requestAnimationFrame.js":function(e,n)!function()(),"./shared/polyfills/string.js":function(e,n)String.prototype.endsWith,”./shared/require-global.js”:function(e,n,t)e.exports=t(“./shared/require-shim.js”),”./shared/require-shim.js”:function(e,n,t)var r=(this.window,function(e)if(!r.hasModule(e))var n=new Error(‘Cannot find module “‘+e+'”‘);throw n.code=”MODULE_NOT_FOUND”,nreturn t(“./”+e+”.js”));r.loadChunk=function(e)return”main”==e?t.e(“main”).then(function(e)t(“./main.js”).bind(null,t))[“catch”](t.oe):”dev”==e?Promise.all([t.e(“main”),t.e(“dev”)]).then(function(e)t(“./shared/dev.js”).bind(null,t))[“catch”](t.oe):”internal”==e?Promise.all([t.e(“main”),t.e(“internal”),t.e(“qtext2”),t.e(“dev”)]).then(function(e)t(“./internal.js”).bind(null,t))[“catch”](t.oe):”ads_manager”==e?Promise.all([t.e(“main”),t.e(“ads_manager”)]).then(function(e)undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined.bind(null,t))[“catch”](t.oe):”publisher_dashboard”==e?t.e(“publisher_dashboard”).then(function(e)undefined,undefined.bind(null,t))[“catch”](t.oe):”content_widgets”==e?Promise.all([t.e(“main”),t.e(“content_widgets”)]).then(function(e)t(“./content_widgets.iframe.js”).bind(null,t))[“catch”](t.oe):void 0,r.whenReady=function(e,n)Promise.all(window.webpackChunks.map(function(e)return r.loadChunk(e))).then(function()n()),r.prefetchAll=function()t(“./settings.js”);Promise.all([t.e(“main”),t.e(“qtext2”)]).then(function().bind(null,t))[“catch”](t.oe),r.hasModule=function(e),r.execAll=function()var e=Object.keys(t.m);tryfor(var n=0;n Pets 101 toggle menu Start your puppy out right and learn the basics of being an awesome pet parent. S.T.A.R. stands for socialization, training, activity, and responsibility, and this program follows the American Kennel Club program while laying a strong foundation. Basic training activities include the name game and loose leash walking, and puppies will work on these commands: sit, down, drop it, give, wait, and follow me. Your puppy will gain socialization skills with other puppies and people, and we’ll introduce puppies in a positive way to everyday objects they may encounter. We’ll discuss housebreaking, crate training, safe toys, and ideas to keep the puppy busy. The class ends with the S.T.A.R. Puppy Test and the pet parent’s Responsible Puppy Pledge. How to train a puppy through the ‘terrible twos’ Old English Sheepdog Smit/Shutterstock Crate training (2-3 months) There are so many books out there about “successful” dog-training techniques, methods, and schools. The amount of information can be overwhelming, and, to make it worse, it’s often contradictory. Search Puppy pads Your puppy needs to learn that people around him, particularly small children, can be a bit unpredictable. But he needs to accept that their unpredictable behavior is not threatening. You can help him do this by imitating a child’s behavior. Try stepping quickly towards his bowl — then drop in a treat. Gently bump into him, while he’s eating, or roll toys nearby — anything to cause a distraction, but drop a treat in the bowl to reward him for continuing to eat calmly. Do this every so often, but not at every meal. If your puppy freezes mid-mouthful, growls or glares at you, stop and try again another time. If this continues, it’s best to seek advice from a veterinary behaviorist or certified dog trainer. How to Train a Puppy to Come When Called Best crate: MidWest Life Stages Folding Dog Crate Paw care Topics: Crate Training, Crate training puppies at night, Crate training dogs, Crate training puppies, Puppy crate training tips, Crate training tips, Crate training schedule, Crate training a puppy, Crate training your dog Stations To achieve this, you need to follow this 5 step process: local ad Search & Rescue I always advise clients to be proactive weather-watchers. If your dog’s potty place is outdoors, consider that potty habits can and might change with the season, and you may have to consider creative and proactive ways to keep your dog’s potty habits strong. For dogs who detest rain, the erection of a portable canopy might just ease the pain. A snow shovel goes a long way in helping small dogs deal with deep snow. Some indoor-outdoor carpet can buffer the heat of summer pavement. Chinchilla advice Beyond How Can I Adopt A Retired Service Dog or Failed Guide Dog?
Tumblr media
dog training
puppy training
how to train a puppy
training a puppy
how to potty train a dog
fbq('track', 'ViewContent', content_ids: 'dogtraining.dknol', ); Potty training a puppy Expert Advice Hi Karen, It sounds like you will need to go back to basics with your potty training and start from scratch as you would with a new puppy. There is some great advice here: https://www.thelabradorsite.com/a-quick-guide-to-house-training-your-labrador-puppy/ You might also like to post up on our friendly forum, where our experienced members are sure to have some good advice! house training older dog | puppy crate training house training older dog | puppy training tips house training older dog | crate training puppies Legal | Sitemap
0 notes
holytheoristtastemaker · 5 years ago
Link
The async / await operators make it easier to implement many async Promises. They also allow engineers to write clearer, more succinct, testable code. To understand this subject, you should have a solid understanding of how Promises work.
Basic Syntax
function slowlyResolvedPromiseFunc(string) { return new Promise(resolve => { setTimeout(() => { resolve(string); }, 5000); }); } async function doIt() { const myPromise = await slowlyResolvedPromiseFunc("foo"); console.log(myPromise); // "foo" } doIt();
There are a few things to note:
The function that encompasses the await declaration must include the async operator. This will tell the JS interpreter that it must wait until the Promise is resolved or rejected.
The await operator must be inline, during the const declaration.
This works for reject as well as resolve.
Nested Promises vs. Async / Await
Implementing a single Promise is pretty straightforward. In contrast, Chained Promises or the creation of a dependency pattern may produce “spaghetti code”. The following examples assume that the request-promise library is available as rp.
Chained/Nested Promises
// First Promise const fooPromise = rp("http://domain.com/foo"); fooPromise.then(resultFoo => { // Must wait for "foo" to resolve console.log(resultFoo); const barPromise = rp("http://domain.com/bar"); const bazPromise = rp("http://domain.com/baz"); return Promise.all([barPromise, bazPromise]); }).then(resultArr => { // Handle "bar" and "baz" resolutions here console.log(resultArr[0]); console.log(resultArr[1]); });
async and await Promises
// Wrap everything in an async function async function doItAll() { // Grab data from "foo" endpoint, but wait for resolution console.log(await rp("http://domain.com/foo")); // Concurrently kick off the next two async calls, // don't wait for "bar" to kick off "baz" const barPromise = rp("http://domain.com/bar"); const bazPromise = rp("http://domain.com/baz"); // After both are concurrently kicked off, wait for both const barResponse = await barPromise; const bazResponse = await bazPromise; console.log(barResponse); console.log(bazResponse); } // Finally, invoke the async function doItAll().then(() => console.log('Done!'));
The advantages of using async and await should be clear. This code is more readable, modular, and testable. It’s fair to note that even though there is an added sense of concurrency, the underlying computational process is the same as the previous example.
Handling Errors / Rejection
A basic try-catch block handles a rejected Promise.
async function errorExample() { try { const rejectedPromise = await Promise.reject("Oh-oh!"); } catch (error) { console.log(error); // "Uh-oh!" } } errorExample();
0 notes
macronimous · 5 years ago
Text
Promise.all — a helpful tool for async #JS https://t.co/22TjgeVvMI #JavaScript #API https://t.co/QtcRHjdHZv
Promise.all — a helpful tool for async #JS https://t.co/22TjgeVvMI #JavaScript #API pic.twitter.com/QtcRHjdHZv
— Macronimous.com (@macronimous) April 30, 2020
from Twitter https://twitter.com/macronimous May 01, 2020 at 05:00AM via IFTTT
0 notes
danrch · 6 years ago
Text
Mapping US unemployment by county, 2016
Mapping US unemployment by county, 2016
Writing d3.js v5 codes to map US unemployment by county in 2016. The version 5 of d3.js makes it easier to import multiple files e.g. json, tsv by using  Promise.all()
  <!DOCTYPE html> <html lang=”en”> <head> <title>US unemployment rate</title> http://d3js.org/d3.v5.min.js https://unpkg.com/topojson@3 <style></style> </head> <body>
Mapping US unemployment by county, 2016
us = “https://unpkg.com/…
View On WordPress
0 notes
codingsrc · 6 years ago
Video
youtube
If you want to know how to use promises in JavaScript and learn everything essential about them in this video you will learn the most important things that you should know about. We are going to go through what the structure of a promise is and what are the states of a promise. We are also going to learn how we can resolve the fulfilled state and how we can handle rejection. We are also going to learn how to use Promise.all and Promise.race and what is the difference between them. So watch this JavaScript ES6 Async tutorial on how to use Promises in your JS code and subscribe to the channel for more videos like this in the future. ► SUBSCRIBE TO CHANNEL https://www.youtube.com/c/codingsrc?sub_confirmation=1 ► VISIT UDEMY COURSES https://www.udemy.com/user/rangelstoilov/ ► VISIT CODINGSRC WEBSITE http://codingsrc.com by CodingSrc
0 notes
theresawelchy · 7 years ago
Text
Making a Map in D3.js v.5
A pretty specific title, huh? The versioning is key in this map-making how-to. D3.js version 5 has gotten serious with the Promise class which resulted in some subtle syntax changes that proven big enough to cause confusion among the D3.js old dogs and the newcomers. This post guides you through creating a simple map in this specific version of the library. If you’d rather dive deeper into the art of making maps in D3 try the classic guides produced by Mike Bostock.
Our objective is to create a map centered on Spain and its neighbouring countries, and add some reasonably big cities onto it. The visualisation will be done in D3.js and the data transformation will be a joint effort between OGR2OGR and R. Prior to launching our D3 playground we need to acquire a base map and a list of locations we want to plot. Datasets obtained from external sources are rarely “plot-ready” and require to be transformed to the right format before use. I’ve collected these under the “preparation tasks” section in this guide. Once we have the data groomed and ready, and a good idea of what we want to visualise, the script is rather straightforward.
Preparation Tasks
#1 As a step 1. I recommend drawing the visualisation you have in mind on a piece of paper. This will help you make the design decisions going forward. 
#2 Download the map that will serve as your base image. I used a map of world administrative boundaries in 1:10M scale obtained from Eurostat. You can check whether the map matches your expectations by uploading it to MapShaper.org. Hovering over a country with the ‘i‘ sign activated will give you information associated with each shape, including the ID you can reference that country by (useful later).
#3 Extract the countries you need for your visualisation to minimise the GeoJSON size. In my scenario I needed to visualise Portugal, Spain, Andorra, France, Switzerland, Italy, Austria, Germany, Hungary, Lichtenstein, Belgium, Luxembourg, Slovenia, Croatia, Slovakia, Bosnia and Herzegovina, Czech Republic, and on the African side Algeria, Morocco, Tunisia, and Libya. I used OGR2OGR to extract these countries from the Eurostat dataset – it was a single line of code:
ogr2ogr -where "FID in ('PT','ES','AD','FR','CH','IT','AT','DE','HU','LI','BE','LU','SI','HR','SK','BA','CZ', 'DZ','MA','TN','LY')" countries.geojson CNTR_RG_10M_2016_4326.geojson
You can look up the FID value in the geojson file or by using the information view in MapShaper. For installation tips and more on OGR2OGR check out my older post Extracting countries from GeoJSON with OGR2OGR. Alternatively you can use Python, R, or even do it by hand.
#4 Tip: perform any dataset transformations or corrections beforehand – it’s often easier to do these outside the D3 realm. I’d advise to use D3 strictly to do data visualisation tasks (plotting, movement, actions). If you need to reproject your data, you might find my post Changing dataset projection with OGR2OGR useful.
#5 Get your locations ready. Put your locations in a csv file and make sure you have these 3 base columns: name, latitude, and longitude.  If you’re planning to populate the map with more than a handful of locations, and your points are missing their geocoordinates, you can look them up using one of the geocoding tools or APIs on the web, for example Map Developers. In case you want to generate a set of locations from scratch, you can use Geonames. Geonames is a geographical database with more than 10M locations, freely distributed under a Creative Commons licence. You’d extract from it the locations that make sense for your visualisation – e.g. by keeping only the highly populated cities. For a guide on how to extract a reasonable set of locations from Geonames take a look at my introduction to Point-in-Polygon in R. I’ll use that dataset in this analysis.
The map
#1 Create an HTML layout: load the D3 v5 library, point to your CSS file, scale SVG to fit your website. All the usual.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>My map</title> <script type="text/javascript" src="https://d3js.org/d3.v5.min.js"></script> <link rel="stylesheet" type="text/css" href="map.css"> <style></style> </head> <body>     <div id="container" class="svg-container"></div>     <script type="text/javascript">     var w = 1400;     var h = 700;     var svg = d3.select("div#container").append("svg").attr("preserveAspectRatio", "xMinYMin meet")     .attr("viewBox", "0 0 " + w + " " + h).style("background","#c9e8fd")     .classed("svg-content", true);
#2 Define your map: choose your projection, specify the center, scale, and zoom. I find D3 in Depth’s Geographic Projection Explorer incredibly useful in preparing the map definition. Check out their documentation on D3’s approach to rendering geographic information, too.
var projection = d3.geoMercator().translate([w/2, h/2]).scale(2200).center([0,40]); var path = d3.geoPath().projection(projection);
#3 Point to the datasets:
var worldmap = d3.json("countries.geojson"); var cities = d3.csv("cities.csv");
#4 Finally we can draw the map. I’m going to load both data sets in my promise syntax, then reference each by its index number. We’ll iterate through the data sets with the clever Promise.all method. Check out my guide to promises in D3.js v.5 if you’re unfamiliar with this new syntax.
Promise.all([worldmap, cities]).then(function(values){     // draw map     svg.selectAll("path")         .data(values[0].features)         .enter()         .append("path")         .attr("class","continent")         .attr("d", path), // draw points     svg.selectAll("circle")         .data(values[1])         .enter()         .append("circle")         .attr("class","circles")         .attr("cx", function(d) {return projection([d.Longitude, d.Lattitude])[0];})         .attr("cy", function(d) {return projection([d.Longitude, d.Lattitude])[1];})         .attr("r", "1px"), // add labels     svg.selectAll("text")         .data(values[1])         .enter()         .append("text")         .text(function(d) {             return d.City;             })         .attr("x", function(d) {return projection([d.Longitude, d.Lattitude])[0] + 5;})         .attr("y", function(d) {return projection([d.Longitude, d.Lattitude])[1] + 15;})         .attr("class","labels"); });
Let’s review what’s happening in the code block by block. Promise.all allows for resolving values from multiple promises at once – in our case the countries geojson and the cities csv file. The Draw Map section plots the base map. In the data call we reference the first value returned by the promise – so the map.csv. The Draw Points section puts our cities on the map – this time by referencing the second data set. The cx and cy coordinates ask for latitude and longitude information and act on one or another (index 0 or 1). Finally, the Add Labels section prints the city names and places them so that they don’t overlap the points. 
#5 Adjust the CSS. This is how my map.css looks like:
.continent {     fill: #f0e4dd;     stroke: #e0cabc;     stroke-width: 0.5; } .circles {     fill: #3c373d; } .labels {     font-family: sans-serif;     font-size: 11px;     fill: #3c373d; }
The full code looks like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>My map</title> <script type="text/javascript" src="https://d3js.org/d3.v5.min.js"></script> <link rel="stylesheet" type="text/css" href="map.css"> <style></style> </head> <body>     <div id="container" class="svg-container"></div>     <script type="text/javascript">     var w = 1400;     var h = 700;     var svg = d3.select("div#container").append("svg").attr("preserveAspectRatio", "xMinYMin meet").style("background-color","#c9e8fd")     .attr("viewBox", "0 0 " + w + " " + h)     .classed("svg-content", true);     var projection = d3.geoMercator().translate([w/2, h/2]).scale(2200).center([0,40]);     var path = d3.geoPath().projection(projection);           // load data   var worldmap = d3.json("countries.geojson"); var cities = d3.csv("cities.csv");     Promise.all([worldmap, cities]).then(function(values){      // draw map     svg.selectAll("path")         .data(values[0].features)         .enter()         .append("path")         .attr("class","continent")         .attr("d", path),  // draw points     svg.selectAll("circle")         .data(values[1])         .enter()         .append("circle")         .attr("class","circles")         .attr("cx", function(d) {return projection([d.Longitude, d.Lattitude])[0];})         .attr("cy", function(d) {return projection([d.Longitude, d.Lattitude])[1];})         .attr("r", "1px"),  // add labels     svg.selectAll("text")         .data(values[1])         .enter()         .append("text")         .text(function(d) {                     return d.City;                })         .attr("x", function(d) {return projection([d.Longitude, d.Lattitude])[0] + 5;})         .attr("y", function(d) {return projection([d.Longitude, d.Lattitude])[1] + 15;})         .attr("class","labels");             });     </script> </body> </html>
Download my files (including the map.html, map.css, countries.geojson, and cities.csv) if you want to try it out on your environment.
Here’s the final visualisation – unfortunately pasted as an image as I haven’t figured out yet how to embed D3js scripts in the new Gutenberg WordPress editor…
Thanks for looking! Let me know in the comments whether you’d improve something or in case you’d spotted an error. Remember to follow my adventures in the data wonderland on Twitter:
Follow @EveTheAnalyst
DataTau published first on DataTau
0 notes