๐ฅWriting a function that returns a promise
function getData() {
return new Promise((resolve, reject) => {
// Perform an asynchronous operation
setTimeout(() => {
// If the operation succeeds, call resolve
resolve('Success');
}, 1000);
});
}
getData().then(result => {
// This function will be called when the promise is fulfilled
console.log(result); // 'Success'
});function getDataFromServer(url) {
return new Promise((resolve, reject) => {
// Perform an asynchronous operation
fetch(url)
.then(response => response.json())
.then(data => {
// If the operation succeeds, call resolve
resolve(data);
})
.catch(error => {
// If the operation fails, call reject
reject(error);
});
});
}
getDataFromServer('https://example.com/data').then(data => {
// This function will be called when the promise is fulfilled
console.log(data);
});Last updated