The code from the Learn JavaScript the Hard Way module JavaScript Level 1 exercises. This is a mirror of the code I have in the book, so if you're struggling you can use this to compare against your attempts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

50 lines
1.9 KiB

// all promise docs I could find fail to mention this feature
// they all say (correctly) that if you return a value from a .then it becomes the
// next .then callback parameter:
let test2 = new Promise((res, rej) => {
res(3);
}).then(x => [x, x + 4]).then(x => [x, x[1] + 5]);
let res2 = test2.then(x => console.log("Then after math", x));
// this produces:
// Then after math [ [ 3, 7 ], 12 ]
// Ok, but if your .then returns a promise, why does it become the next promise but
// not the next promise. Watch.
let outer_promise = new Promise((res, rej) => {
res(1);
});
// now I'm going to return this one in first_then
let inner_promise = new Promise((res, rej) => {
console.log("inner promise running");
res("INNER_PROMISE");
});
// log the parameter so you can see it's 1
let first_then = outer_promise.then(x => {
console.log("first_then", x);
return inner_promise; // return the pomise here
});
// at this point you would expect x to == inner_promise, but instead it will equal "INNER PROMISE"
let last_then = first_then.then(x => {
// wtf? ok so then that means when I call first_then.then I should be working on inner_promise right?
console.log("first_then === outer_promise", first_then === outer_promise);
console.log("first_then === inner_promise", first_then === inner_promise);
console.log("first_then === last_then", first_then === last_then);
console.log("first_then === first_then", first_then === first_then);
// no, not only is it using inner_promise as the next .then, it's wrapping inner_promise with a promise so
// that my call to .then is going through...two promises? Wtf?
// The expectation is that first_then === inner_promise since I returned that but instead it's a whole other 3rd
// promise adding a layer to the layer.
// and here's the value "INNER_PROMISE", not a inner_promise like I returned.
console.log("Then after promise", x);
});