Last active
April 21, 2017 12:50
-
-
Save SergeyLipko/f3aa2ce59ade9b6b4ae61c12cd8923a1 to your computer and use it in GitHub Desktop.
All about async await functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Основная идея async await - избавиться от коллбеков, которые использую промисы, интуитивно понятный механизм | |
отлова ошибок через try catch ну и последовательная обработка, представляющая собой "синхронное" представление | |
*/ | |
function baz() { | |
return new Promise((res) => { | |
setTimeout(() => { | |
res('hey baz') | |
}, 500) | |
}); | |
} | |
function dan() { | |
return new Promise((res) => { | |
setTimeout(() => { | |
res('hey dan') | |
}, 500) | |
}); | |
} | |
// * * * * * Стандартное использование * * * * * | |
async function getDataAsync() { | |
try { | |
const baz = await baz(); | |
const dan = await dan(); | |
// после того, как baz и dan выполнятся | |
console.log('Do something with', baz, dan); | |
} catch (e) { | |
throw new Error(e); | |
} | |
} | |
// * * * * * Вместе с Promise.all() * * * * * | |
async function handleAll() { | |
let result = await Promise.all([baz(), dan()]) | |
console.log(result); | |
} | |
// * * * * * Использование в контексте Redux * * * * * | |
export function logout(router) { | |
return async (dispatch) => { | |
try { | |
const {data: {success, message}} = await axios.get('/logout'); | |
(success) | |
? dispatch({ type: LOGOUT_SUCCESS }) | |
: dispatch({ type: LOGOUT_FAILURE, message }); | |
} catch (e) { | |
dispatch({ type: LOGOUT_FAILURE, e.data.message }); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment