Last active
August 31, 2018 09:18
-
-
Save Anna-Myzukina/41a94a4d894bb4f8f906ddf3161ce21a to your computer and use it in GitHub Desktop.
Promise It Won’t Hurt
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
//Using setTimeout, print the string 'TIMED OUT!' after 300ms. | |
setTimeout(() => { | |
console.log('TIMED OUT!') | |
}, 300) |
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
/**Create a function `alwaysThrows` that throws an `Error` withtext `"OH NOES"`; | |
* Create a function `iterate` that prints the first argument(an integer) to it and then returns that argument + 1; | |
* Create a promise chain using `Promise.resolve` that wraps your iterate method,then a series of iterations that attempts to perform `iterate` a total of 10 times. | |
* Attach a rejection handler at the bottom of your chain to print the`error.message` using `console.log`. | |
* Insert a call to `alwaysThrows` after your 5th call of `iterate` | |
If you have done this correctly, your code should print 1,2,3,4,5, | |
"[Error: OH NOES]". It's important to notice that the thrown exception was | |
turned into a rejected promise which caused the rejected promise to | |
travel down the promise chain to the first available rejection handler | |
*/ | |
'use strict'; | |
function alwaysThrows() { | |
throw new Error("OH NOES"); | |
} | |
function iterate(int) { | |
console.log(int); | |
return (int + 1); | |
} | |
function onReject(error) { | |
console.log(error.message); | |
} | |
Promise.resolve(iterate(1)) | |
.then(iterate) | |
.then(iterate) | |
.then(iterate) | |
.then(iterate) | |
.then(alwaysThrows) | |
.then(iterate) | |
.then(iterate) | |
.then(iterate) | |
.catch(onReject); |
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
/*Create a function all that accepts two promises as arguments. This all | |
function should do all of the following: | |
Create an internal promise in whatever way you see fit. | |
Create a counter variable with initial value of 0. | |
Attach then fulfillment handlers to both promises and increment the internal | |
counter when the handlers are called. | |
When the counter reaches 2, fulfill the internal promise with an array | |
containing both values. | |
Finally return that internal promise to the user. | |
After you finish writing your all function, pass getPromise1() and | |
getPromise2() into your new function and then attach console.log as a | |
fulfillment handler to the promise returned by your function. These two | |
promise-returning functions will be provided to you in the global scope | |
*/ | |
'use strict'; | |
function all(promise1, promise2) { | |
var counter = 0; | |
var array = []; | |
return new Promise(function(fulfill, reject) { | |
promise1.then(val => { | |
array[0] = val; | |
counter++; | |
if (counter >= 2) { | |
fulfill(array); | |
} | |
}); | |
promise2.then(val => { | |
array[1] = val; | |
counter++; | |
if (counter >= 2) { | |
fulfill(array); | |
} | |
}); | |
}); | |
} | |
all(getPromise1(), getPromise2()) | |
.then(console.log); |
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 JSON from [http://](http://) and console.log it. | |
There are several things you will want to know: | |
* `q-io`'s `http` module has a `read` method which returns a promise for thecontent of a successful (status 200) HTTP request. | |
* Parse the returned JSON and `console.log` it for much win | |
*/ | |
var qhttp = require('q-io/http'); | |
qhttp.read("http://localhost:1337") | |
.then(function(json) { | |
console.log(JSON.parse(json)); | |
}) | |
.catch(console.error); |
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
/*Let's talk to two remote processes over HTTP being run by your friend | |
and mine, "localhost". | |
* Port 7000: Faux session cache (Redis or some such thing) | |
* Port 7001: Faux database (MongoDB, LevelDB, Postgres, etc) | |
As in the previous lesson, use the q-io module to create promises | |
as wrappers for HTTP responses. Hint: You will probably need more | |
than one promise… | |
* Send an HTTP GET request to the session cache on port 7000. A stringwill be returned to you representing a user ID. | |
* Grab that ID from the session response and send an HTTP GET request toyour database on port 7001 to | |
the url `localhost:7001/<id>`. | |
* If successfully done, your database will return a user object.`console.log` it to win many nerd-points. | |
*/ | |
var qhttp = require('q-io/http'); | |
qhttp.read("http://localhost:7000/") | |
.then(function(id) { | |
return qhttp.read("http://localhost:7001/" + id); | |
}) | |
.then(function(json) { | |
console.log(JSON.parse(json)); | |
}) | |
.catch(console.error) |
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
/* | |
Create a promise. Have it fulfilled with a value of 'FULFILLED!' in | |
executor after a delay of 300ms, using setTimeout. | |
Then, print the contents of the promise after if has been fulfilled by passing | |
console.log to then. | |
*/ | |
'use strict'; | |
var promise = new Promise(function (fulfill, reject) { | |
// Your solution here | |
setTimeout(() => { | |
fulfill('FULFILLED!') | |
}, 300) | |
}); | |
// Your solution here | |
promise.then(console.log); | |
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
/*Create a promise that after a delay of 300ms, rejects with an Error object. | |
The Error object should be constructed with parameter 'REJECTED!', which is | |
the textual message of the error. | |
Create a function onReject to print error.message using console.log. Pass | |
this function as a rejection handler to the then method of your promise. | |
*/ | |
'use strict'; | |
var promise = new Promise(function (fulfill, reject) { | |
// Your solution here | |
setTimeout(() => { | |
reject(new Error("REJECTED!")); | |
}, 300); | |
}); | |
function onReject(error) { | |
// Your solution here | |
console.log(error.message); | |
} | |
// Your solution here | |
promise.then(null, onReject); |
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
/*First, create a promise using the Promise constructor as we have been doing. | |
In the promise’s executor, immediately attempt to fulfill the promise with a | |
value of 'I FIRED' | |
Then, after the fulfill call, immediately try to reject the promise with an | |
Error created with parameter 'I DID NOT FIRE'. | |
After the promise creation, create a function onRejected with one parameter | |
error that prints the Error’s message with console.log. | |
Lastly, pass console.log and the function you just created as the success | |
and rejection handlers respectively. | |
If successful, your script should only log “I FIRED” and should not log | |
“I DID NOT FIRE”. | |
*/ | |
'use strict' | |
var promise = new Promise(function (fulfill, reject) { | |
fulfill('I FIRED') | |
reject(new Error('I DID NOT FIRE')) | |
}); | |
var onRejected = function (error) { | |
console.log(err.message); | |
} | |
promise.then(console.log, onRejected); |
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
/*First, create a promise using the Promise constructor. | |
In the promise’s executor, immediately fulfill the promise with a value of | |
'PROMISE VALUE'. | |
After the creation of the promise, pass console.log as the success handler to | |
the promise. | |
Finally, print out “MAIN PROGRAM” with console.log | |
*/ | |
'use strict'; | |
var promise = new Promise(function (fulfill, reject) { | |
fulfill('PROMISE VALUE'); | |
}); | |
promise.then(console.log); | |
console.log('MAIN PROGRAM'); |
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
/*We don’t have any specific task we’d like to assign to you for this lesson. | |
Feel free to explore all three functions at your own pace. When you are | |
preparing to submit though, make sure you are using at least catch and one | |
of Promise.resolve and Promise.reject | |
*/ | |
'use strict'; | |
var promise = Promise.reject(new Error('SECRET VALUE') | |
).then(null, function(error) { | |
console.log(error.message); | |
}).catch(function(error) { | |
console.log(error.message); | |
}); | |
/* | |
'use strict'; | |
var message; | |
var promise; | |
function randomBytes(n) { | |
return (Math.random() * Math.pow(256, n) | 0).toString(16); | |
} | |
message = | |
'A fatal exception ' + randomBytes(1) + ' has occurred at ' + | |
randomBytes(2) + ':' + randomBytes(4) + '. Your system\nwill be ' + | |
'terminated in 3 seconds.'; | |
promise = Promise.reject(new Error(message)); | |
promise.catch(function (err) { | |
var i = 3; | |
process.stderr.write(err.message); | |
setTimeout(function boom() { | |
process.stderr.write('\rwill be terminated in ' + (--i) + ' seconds.'); | |
if (!i) { | |
process.stderr.write('\n..... . . . boom . . . .....\n'); | |
} else { | |
setTimeout(boom, 1000); | |
} | |
}, 1000); | |
}); | |
*/ |
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
/*This task will allow you to demonstrate an understanding how to chain promises | |
together using then. | |
Two functions will be provided as global functions that you can use: first | |
and second. | |
Call the first function in your program. first() will return a promise that | |
will be fulfilled with a secret value. | |
Call the second with the fulfilled value of first. Return the promise returned | |
by second in your onFulfilled callback. | |
Finally, print the fulfilled value of that new promise with console.log | |
*/ | |
'use strict'; | |
/* global first, second */ | |
var firstPromise = first(); | |
var secondPromise = firstPromise.then(function (val) { | |
return second(val); | |
}); | |
secondPromise.then(console.log); |
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
/*Construct a promise chain that returns values to prove to yourself that | |
promise handlers will wrap your returned values in promises allowing | |
additional chaining. | |
* Declare a function `attachTitle` which prepends `'DR. '` to its firstargument and returns the result. | |
* Create a fulfilled promise with a value of `'MANHATTAN'`. | |
* Build a promise chain off the promise we just constructed that first calls`attachTitle` then calls `console.log`. | |
If your program runs successfully, it should print out “DR. MANHATTAN” which | |
is extremely exciting. | |
*/ | |
'use strict'; | |
function attachTitle(name) { | |
return 'DR. ' + name; | |
} | |
var promise = new Promise(function(fulfill, reject){ | |
fulfill('MANHATTAN'); | |
}) | |
.then(attachTitle) | |
.then(console.log); |
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
/*Some invalid JSON will be available on process.argv[2]. | |
* Build a function called `parsePromised` that creates a promise,performs `JSON.parse` in a `try`/`catch` block, and fulfills or rejectsthe promise depending on whether an error is thrown.**Note:** your function should synchronously return the promise! | |
* Build a sequence of steps like the ones shown above that catchesany thrown errors and logs them to the console. | |
*/ | |
'use strict' | |
function parsePromised(json) { | |
return new Promise(function (fulfill, reject) { | |
try { | |
fulfill(JSON.parse(json)); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
} | |
function onReject(err) { | |
console.log(err.message); | |
} | |
parsePromised(process.argv[2]).then(null, onReject); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment