Skip to content

Instantly share code, notes, and snippets.

@SergeyLipko
Last active April 19, 2017 10:54
Show Gist options
  • Save SergeyLipko/d0eb7dd57ccf46ae7513a55bd58566e2 to your computer and use it in GitHub Desktop.
Save SergeyLipko/d0eb7dd57ccf46ae7513a55bd58566e2 to your computer and use it in GitHub Desktop.
All about promises
/*
* Сильные стороны
* 1) Композиция промисов (chaining)
* 2) API - методы типа all и race
*/
// * * * * * Default composition * * * * *
// всегда использовать return внутри then или выдавать ошибку при помощи throw
function promiseAxios() {
axios.get("http://localhost:8080/api/user")
.then(users => {
// здесь возвращается просто синхронное значение
return users;
})
.then(users => {
console.log(users);
// если внутри then стартует новый асинхронный процесс, то для того, чтобы
// оставшаяся часть цепочки выполнилась после его окончания, необходимо вернуть промис
// иначе операции выполнятся одновременно
// передаем результат выполнения промиса в следующий then
// если бы промис не возвращался, а просто выполнялся,
// следующий then получил бы undefined, a не user
// таким обзаром, если then не возвращает никакого значения (синхронного или аснхронного)
// в итоге по-умолчанию возвращается бесполезный undefined, который и попадает в
// следующий then
return axios.get("http://localhost:8080/api/user/589829329713c72c98a58edd")
})
.then(user => {
const { _id } = user.data;
// передаем результат выполнения промиса в следующий then
return axios.delete(`http://localhost:8080/api/user/${_id}`)
})
.then(res => {
console.log('response', res);
})
.catch(e => {
throw new Error(e);
})
}
// * * * * * Promise.all * * * * *
function myPromiseAll() {
// выполнение нескольких асинхронных операций одновременно и обработка
// их результата
Promise.all([
axios.get("http://localhost:8080/api/user/589829339713c72c98a58ede"),
axios.get("http://localhost:8080/api/user/58982dfe75214d2d9609ed5a"),
axios.get("http://localhost:8080/api/user/589ac6da212b1c4d5c289bd8")
]).then(res => {
console.log(res); // [Object, Object, Object]
});
}
// * * * * * Promise.race * * * * *
function myPromiseRace() {
// результатом будет только первый успешно выполнившийся промис из списка,
// остальные игнорируются
Promise.race([
axios.get("http://localhost:8080/api/user/589829339713c72c98a58ede"),
axios.get("http://localhost:8080/api/user/58982dfe75214d2d9609ed5a"),
axios.get("http://localhost:8080/api/user/589ac6da212b1c4d5c289bd8")
]).then(res => {
console.log(res);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment