Это старая версия документа!
ПРОМИСИ
Виконання відкладених задач. Асінхронно.
Состояния промиса
- ожидание (panding)
- исполнен (resolve)
- отклонен (reject)
обявление промиса (Promise)
const myPromise = new Promise ((resolve, reject)=>{
//Віполнение асинхронного действия нужно в результате візвать одну из функций resolve или reject
})
Обробка резуьтата промиса (.then)
myPromse
.then(value => {
//действие в случае успешного віполнения
})
.catch (error=>{
//дія у випадку помилки
})
- Приклад 1
const isSuccess = true;
// Create promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (isSuccess) {
resolve("Success! Value passed to resolve function");
} else {
reject("Error! Error passed to reject function");
}
}, 2000);
});
// Registering promise callbacks
promise.then(
value => {
console.log(value); // "Success! Value passed to resolve function"
},
error => {
console.log(error); // "Error! Error passed to reject function"
}
);
У змінну promise буде записаний проміс (об'єкт) у стані pending, а через дві секунди, щойно буде викликаний resolve() або reject(), проміс перейде у стан fulfilled або rejected, і ми зможемо його обробити. Якщо функції onResolve і onReject містять складну логіку, їх для зручності оголошують як зовнішні функції і передають у метод then() за ім'ям.
Обробка помилки catch()
На практиці в методі then() обробляють тільки успішне виконання промісу. Помилку його виконання обробляють у спеціальному методі catch() для «відловлювання» помилок.
const isSuccess = true;
// Create promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (isSuccess) {
resolve("Success! Value passed to resolve function");
} else {
reject("Error! Error passed to reject function");
}
}, 2000);
});
// Registering promise callbacks
promise
.then(value => {
console.log(value); // "Success! Value passed to resolve function"
})
.catch(error => {
console.log(error); // "Error! Error passed to reject function"
});
const isSuccess = true;
// Create promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (isSuccess) {
resolve("Success! Value passed to resolve function");
} else {
reject("Error! Error passed to reject function");
}
}, 2000);
});
// Registering promise callbacks
promise
.then(value => console.log(value)) // "Success! Value passed to resolve function"
.catch(error => console.log(error)) // "Error! Error passed to reject function"
.finally(() => console.log("Promise settled")); // "Promise settled"
Іньші приклади
- Приклад 2 (web)
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
console.log(response) // показує поний склад відповіді від серверу (з тех.дннними)
return response.json() //поверта тільки данні після ковераації з json
})
.then(json => console.log(json))
.catch(error => console.log(error.message))
- Приклад 3 (node.js)
const getData =(url)=>
new Promise ((resolve, reject)=>
fetch(url)
.then(response=>response.json())
.then(json => resolve(json))
.catch(error=>reject(error))
)
getData('https://jsonplaceholder.typicode.com/todos')
.then(data=>console.log(data))
.catch(error=>console.log(error))