Last active
May 11, 2018 18:50
-
-
Save bschwartz757/3e1bbcb575ee3e7404ffd50c468b470b to your computer and use it in GitHub Desktop.
Parallel async function examples and string search examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////// FETCH URLS ASYNCHRONOUSLY /////////// | |
/* Client side, works in Chrome 55 and Firefox 52 without transpilation */ | |
//https://blogs.msdn.microsoft.com/typescript/2016/11/08/typescript-2-1-rc-better-inference-async-functions-and-more/ | |
//interesting (opinionated) article on fetch vs. xhr: https://jakearchibald.com/2015/thats-so-fetch/ | |
async function fetchURLs() { | |
try { | |
// Promise.all() lets us coalesce multiple promises into a single super-promise | |
var data = await Promise.all([ | |
/* Alternatively store each in an array */ | |
// var [x, y, z] = await Promise.all([ | |
// parse results as json; fetch data response has several reader methods available: | |
//.arrayBuffer() | |
//.blob() | |
//.formData() | |
//.json() | |
//.text() | |
fetch('https://jsonplaceholder.typicode.com/posts').then((response) => response.json()),// parse each response as json | |
fetch('https://jsonplaceholder.typicode.com/albums').then((response) => response.json()), | |
fetch('https://jsonplaceholder.typicode.com/users').then((response) => response.json()) | |
]); | |
for (var i of data) { | |
console.log(`RESPONSE ITEM \n`); | |
for (var obj of i) { | |
console.log(obj); | |
//logger utility method, logs output to screen | |
console.log(obj); | |
} | |
} | |
} catch (error) { | |
console.log(error); | |
} | |
} | |
fetchURLs(); | |
/* As of v1.5, jQuery also has a $.deferred() method which I have used in production. | |
It is promise-like but is not as elegant a solution and likely has worse performance. | |
It could be used in this context but may not perform parallel requests. */ | |
/* NodeJS version */ | |
//uses the `request` package which makes working with Node's native http methods easier | |
const request = require('request'); | |
var requestAsync = function(url) { | |
return new Promise((resolve, reject) => { | |
var req = request(url, (err, response, body) => { | |
if (err) return reject(err, response, body); | |
resolve(JSON.parse(body)); | |
}); | |
}); | |
}; | |
const urls = [ | |
'https://jsonplaceholder.typicode.com/posts', | |
'https://jsonplaceholder.typicode.com/albums', | |
'https://jsonplaceholder.typicode.com/users' | |
]; | |
/* Works as of Node 7.6 */ | |
var getParallel = async function() { | |
//transform requests into Promises, await all | |
try { | |
var data = await Promise.all(urls.map(requestAsync)); | |
} catch (err) { | |
console.error(err); | |
} | |
console.log(data); | |
} | |
getParallel(); | |
/////// FETCH URLS ASYNCHRONOUSLY /////////// | |
/////// STRING SEARCH EXAMPLES /////////// | |
<div id="placeholder"> | |
Output goes here | |
</div> | |
const string = 'there is a cow in a field'; | |
function print(result) { | |
console.log(result); | |
document.getElementById('placeholder') | |
.innerText = result; | |
} | |
//String.indexOf(); | |
//returns index of first matched char, or -1 | |
function stringIndex(subStr) { | |
var found = string.indexOf(subStr); | |
print(found); | |
} | |
//stringIndex('stuff'); | |
//String.search(); | |
//same behavior as indexOf(); | |
function searchString(subStr) { | |
var found = string.search(subStr); | |
print(found); | |
} | |
//searchString(' is a '); | |
//RegExp.test(); | |
//searches using regex, returns boolean | |
//similar to string.search(), except return is bool | |
function testString(re) { | |
console.log(re.source); | |
var found = re.test(string); | |
print(found); | |
} | |
//testString(/there/); | |
//RegExp.exec(); | |
//returns an array of info (search term, index, input) or null | |
function execString(re) { | |
console.log(re.source); | |
var found = re.exec(string); | |
print(found); | |
} | |
//execString(/cow/); | |
//String.match(); | |
//returns an array of info (search term, index, input) or null | |
//similar to RegExp.exec(); | |
function matchString(re) { | |
console.log(re.source); | |
var found = string.match(re); | |
print(found); | |
} | |
//matchString(/there is a/); | |
//String.replace(); | |
//Searches for substr, and replaces if found | |
//can search by RegExp, and replace using fn | |
//returns a new string, orig string unchanged | |
function replaceString(subStr, newStr) { | |
print(string.replace(subStr, newStr)); | |
} | |
//replaceString('is a cow', 'are cows'); | |
//String.replace(); | |
//Uses RegExp or string to split string into | |
//array of substrings | |
function splitString(separator) { | |
var stringArr = string.split(separator); | |
print(stringArr); | |
} | |
//splitString(' '); | |
function reverseString(separator, newSeparator) { | |
var stringArr = string.split(separator) | |
.reverse() | |
.join(newSeparator); | |
print(stringArr); | |
} | |
reverseString(' ', ' / '); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment