Promise <pending>
Why use Promises in your code?
To handle asynchronous operations in JavaScript.
You want your code to be still working and running while carrying out api calls for example.
A promise represents a single asynchronous operation that hasn’t been completed yet, but is expected in the future. The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
There are three states of promises, pending, fulfilled and rejected.
Fetch()
The fetch function takes one argument, which is the url you want to fetch data from and returns a promise that resolves to the response of that request.
It allows attaching “listener” to it using .then(…) that can respond to the result value (response to the request). The .then(…) returns again a promise object that will give the result forward.
A fetch() is a network operation. To avoid stopping the app until we get a reply from the network, we defer it to the background and give ourselves the promise that it will be completed eventually.
fetch(url).then((data) => data.json()) means that we fetch the url, wait for data to come in, get the json representation of the data and wait for that too (data.json() is a promise too)
The next .then handler always gets the value of the chained promise which was returned before.
If the server hasn’t replied to our request yet, the promise is in the pending state.
async and await with Promises
You can use async and await using Promises
Example:
async function beautifulFunctionName(url) {let response = await fetch(url);
console.log(response);return response;}console.log(beautifulFunctionName(url)); // Returns Promise
This is basically the same without await and async:
function beautifulFunctionName(url) { return fetch(url)
.then(response => {
console.log(response); // Logs the response
return response;
}
);}console.log(beautifulFunctionName(url)); // Returns Promise
Why is my promise logging pending?
The promise will always log pending as long as its results are not resolved yet.
You must call .then on the promise to capture the results regardless of the promise state (resolved or still pending):
Promises are forward direction only; You can only resolve them once.
If your Promise is pending, complete it by
FunctionWhichReturnsAPromise()
.then(function(result){
console.log(result)
})