blink/tutorials/2_promise_chaining.js

49 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-10-05 16:37:07 +02:00
// https://javascript.info/promise-chaining
// .then() returns a new Promise when you do "return",
// internally calling resolve().
2024-02-23 11:17:02 +01:00
new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1);
}).then(function (result) {
console.log(result);
return result * 2;
}).then(function (result) {
console.log(result);
return result * 2;
}).then(function (result) {
console.log(result);
return result * 2;
});
2023-10-05 16:37:07 +02:00
/*
2024-02-23 11:17:02 +01:00
It will print
2023-10-05 16:37:07 +02:00
1
2
4
*/
/*
It means that "then" is internally implemented roughly as follows:
2024-02-23 11:17:02 +01:00
2023-10-05 16:37:07 +02:00
function then(f){
return new Promise(function(resolve, reject) {
resolve(f());
})
}
*/
// Another example:
fetch('http://www.fsf.org')
// .then below runs when the remote server responds
2024-02-23 11:17:02 +01:00
.then(function (response) {
2023-10-05 16:37:07 +02:00
// response.text() returns a new promise that resolves with the full response text
// when it loads
return response.text();
})
2024-02-23 11:17:02 +01:00
.then(function (text) {
2023-10-05 16:37:07 +02:00
// ...and here's the content of the remote file
console.log(text);
2024-02-23 11:17:02 +01:00
});