-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08_chainFunctionResult.js
41 lines (36 loc) · 1.33 KB
/
08_chainFunctionResult.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
this is exactly the same function as 07_returnPromiseFromFunction,
simplified by removing unnecessary variables and using es6 syntax
*/
const returnsAPromise = () =>
Promise.resolve(42)
.then(value => {
console.log("first then:", value);
return value + 50;
})
.then(value => {
console.log("second then:", value);
return value;
})
.then(value => {
console.log("third then:", value);
return "return value of the third promise";
});
var functionResult = returnsAPromise(); // functionResult is still a promise, which will resolve with the return value of the last 'then' (the third one)
var x = functionResult
.then(function(result) {
// we can access the value by simply chaining another 'then' to the return value of 'returnsAPromise'
console.log(result);
return result; // to reuse the same result in 2 different then block, we can return it again.
})
.then(function(result) {
console.log(result + " used a second time");
return result;
});
console.log("functionResult", x);
/*
review the code and try to trace the results before running the examples.
what will 'x' be?
remember: a promise chain once started can not be made syncronous again, the correct
way to process things in order after the resolution is by chaining more 'then' statements
*/