Promise creation :
- Using promises, you can avoid the inversion of control problem.
- A promise is said to be settled if it not pending, i.e it is either fulfilled or rejected.
- An unresolved promise is always in the pending state. A resolved promise may be pending or fulfilled, or rejected.
- Calling the resolve function means your promise is fulfilled, and calling the reject function means your promise is rejected(error).
- You can't resolve or reject multiple times. You can resolve or reject only once.
- resolve or reject functions send a signal to the promise object to update their status(state) and value, and move ahead if there is any code.
- If you call resolve or reject again and again, then the promise object ignores it because it is already settled.
function fetchData(url) {
return new Promise((resolve, reject) => {
console.log("started.");
setTimeout(() => {
resolve("success..");
}, 4000);
console.log(" promise ended but it is not fulfiiled..");
});
}
fetchData("[www.google.com](<http://www.google.com/>)")
Explanation: "started" on console and it reaches to setTimeout method, then setTimeout is registered in the web environment and starts its timer. Execute the remaining code and return the promise object, but its state is pending and the value is undefined. After some time promise is fulfilled, then the promise state is updated from pending to fulfilled, and the value is the actual value.
Note: Creation of a promise involves a synchronous piece of code; it will wait, otherwise it won't wait.
- callback is having a long sync piece of code, so JavaScript will have to wait for the promise object creation with the fulfilment state.
- object will get created easily as there is no blocking piece of code, but initially it will be pending. as the fulfilment happens after some time.
- .then() method function takes a function as an argument that we want to execute after the promise is fulfilled, and the argument function takes value property as a parameter.
- .then method itself returns a new promise. You can store it in a variable.
- .then() method doesn't return a value, then the value is undefined.
example :
let promise= fetchData("[www.google.com](<http://www.google.com/>)")
let otherPromise = promise.then((value)=>{
return "shivaji"
})
otherPromise.then((value)=>{
console.log("the otherPromise value is ", value)
})
promise.resolve() : this method gives the fulfilled promise(resolved). you can chain with .then() method.
snippet 1 :