Last active
March 18, 2017 08:33
-
-
Save mariusz-blaszczak/8525e3bd7e2f195d2c78ebe2fe6903c3 to your computer and use it in GitHub Desktop.
Promise example. https://scotch.io/tutorials/javascript-promises-for-dummies
This file contains 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
const canStart = (response) => { | |
return new Promise((resolve, reject) => { | |
if (response) { | |
resolve(response); | |
} else { | |
reason = new Error("cant start. forbiden"); | |
reject(reason); | |
} | |
}); | |
} | |
const sumNumbersWithApi = (a, b) => { | |
console.log(`a i b to: ${a} i ${b}`); | |
const url = `https://stark-escarpment-75299.herokuapp.com/?a=${a}&b=${b}`; | |
return fetch(url) | |
.then(response => response.json()) | |
.then(response => parseInt(response['response'])) | |
.catch((error) => { | |
console.log("there was error in fetch:", error.message); | |
}); | |
}; | |
const putInConsole = (response) => { | |
console.log("policzona suma: " + response); | |
return Promise.resolve(response); | |
}; | |
canStart(true) | |
.then(response => sumNumbersWithApi(3, 2)) | |
.then(putInConsole) | |
.then(response => sumNumbersWithApi(3, response)) | |
.then(putInConsole) | |
.then(response => sumNumbersWithApi(3, response)) | |
.then(response => canStart(false)) | |
.then(response => sumNumbersWithApi(3, response)) | |
.then(putInConsole) | |
.catch(error => console.log(error.message)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment