Before answer the question about "What's Promise?", we need to know how does JavaScript execute codes.
unresolved
resolved
rejected
The vast majority of use promises is working with Ajax requests but we can make promises without Ajax requests. Moreover, the promises are used to solve the issue of asynchronous code. Note that the trick to dealing with asynchronous code is through how we call resolve()
and reject()
.
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
// reject()
resolve();
}, 3000);
});
promise
.then(() => console.log("Finally finished!"))
.then(() => console.log("I was also ran!"))
.catch(() => console.log("uh oh!!"));
The fetch()
helper is the feature that is just like promises implemented inside the browsers already.
url = 'http://jsonplaceholder.typicode.com/posts/'
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
Because the fetch()
helper only catch when the network request flat out fails. It's really highly recommend that still use Ajax utility libraries like axios
or jQuery
.