Skip to content

Instantly share code, notes, and snippets.

@DaleSeo
Created December 13, 2018 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaleSeo/c366c0a8c1416a89adb1f64975be8f64 to your computer and use it in GitHub Desktop.
Save DaleSeo/c366c0a8c1416a89adb1f64975be8f64 to your computer and use it in GitHub Desktop.
JS Async Promise
findUser(1)
.then(function(user) {
console.log("user:", user);
});
function findUser(id) {
return new Promise(function (resolve) {
setTimeout(function() {
console.log("waited 0.1 sec.");
const user = {
id: id,
name: "User" + id,
email: id + "@test.com"
};
resolve(user);
}, 100);
});
}
function devide(numA, numB) {
return new Promise((resolve, reject) => {
if (numB === 0)
reject(new Error("Unable to devide by 0."));
else
resolve(numA / numB);
});
}
devide(8, 2)
.then(result => console.log("성공:", result))
.catch(error => console.log("실패:", error));
devide(8, 0)
.then(result => console.log("성공:", result))
.catch(error => console.log("실패:", error));
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => console.log("response:", response))
.catch(error => console.log("error:", error));
fetch()
.then(response => console.log("response:", response))
.catch(error => console.log("error:", error));
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(post => console.log("post:", post))
.catch(error => console.log("error:", error));
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(post => post.userId)
.then(userId => "https://jsonplaceholder.typicode.com/users/" + userId)
.then(url => fetch(url))
.then(response => response.json())
.then(user => console.log("user:", user))
.catch(error => console.log("error:", error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment