Promises
developers law' wa'DIch yajbe' concept: Promises.
Promises JavaScript Daq asynchronous operations Dun vaD chenmoH. callbacks tlhoch nested, laD Qatlh, maintain Qatlh - Promises Qotlh. Promises asynchronous operations clean 'ej simple Qu'.
chay' Promises Qu'? Promise object ghaH, operation asynchronous Qu' 'ej value pagh error nob. Promise wej state Daq:
- Pending: wa'DIch state, chenmoHta'DI'.
- Fulfilled: state Promise Qapla' 'ej value nob.
- Rejected: state Promise error jach.
misvam yIlaD:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() >= 0.5) {
resolve("Success!");
} else {
reject("Error!");
}
}, 1000);
});
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
misvam Daq Promise chenmoH, wa' lup aprIl "Success!" pagh "Error!" nob (random mI' 0,5 law' pagh puS). "then" method Qapla' Qu', "catch" method error Qu'.
Promises chain laH, complex asynchronous operations Qu'. naDev misvam: Promises chain, asynchronous task law' step Daq Qu':
function stepOne() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step One Complete");
resolve();
}, 1000);
});
}
function stepTwo() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step Two Complete");
resolve();
}, 1000);
});
}
function stepThree() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step Three Complete");
resolve();
}, 1000);
});
}
stepOne()
.then(() => stepTwo())
.then(() => stepThree())
.then(() => console.log("All Steps Complete"));
misvam Daq wej function chenmoH, asynchronous operation Qu' 'ej Promise nob. "then" method chain, step Hoch Dung step pIm Qu'.