promese java script code example
Example 1: js return a promise
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
Example 2: what is promise in javascript
Promises make async javascript easier as they are easy to use and write than callbacks. Basically , promise is just an object , that gives us either success of async opertion or failue of async operations