Last active
August 18, 2016 12:33
-
-
Save derzunov/464a6a05524404d24e9ef8dc8b881783 to your computer and use it in GitHub Desktop.
Async/Await example
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
function asyncFunc1 () { | |
return new Promise(function(resolve, reject) { | |
setTimeout( () => resolve({message: "First done!"}), 300 ); | |
}); | |
}; | |
function asyncFunc2 () { | |
return new Promise(function(resolve, reject) { | |
setTimeout( () => resolve({message: "Second done!"}), 200 ); | |
}); | |
}; | |
function asyncFunc3 () { | |
return new Promise(function(resolve, reject) { | |
setTimeout( () => resolve({message: "Third done!"}), 100 ); | |
}); | |
}; | |
function callback ( data ) { console.log( data.message ) }; | |
function start () { | |
// Работают асинхронно | |
asyncFunc1().then(callback); | |
asyncFunc2().then(callback); | |
asyncFunc3().then(callback); | |
}; | |
// Некрасиво :( | |
function startChain () { | |
asyncFunc1().then(function( data ) { | |
console.log(data.message ); | |
return asyncFunc2(); | |
}).then(function(data_2) { | |
console.log(data_2.message); | |
return asyncFunc3(); | |
}).then(function(data_3) { | |
console.log(data_3.message); | |
// Тут делаем наши дела после того, как все функции отработали | |
console.log("Всё!"); | |
}); | |
}; | |
// Красиво :) | |
async function startAsyncAwait () { | |
// Работают синхронно, в нужном нам порядке | |
let data1 = await asyncFunc1(); | |
let data2 = await asyncFunc2(); | |
let data3 = await asyncFunc3(); | |
console.log("startAsync:", data1.message, data2.message, data3.message); | |
}; | |
// Раскомментируй функцию, которую хочешь проверить в работе | |
start(); | |
//startChain(); | |
//startAsyncAwait(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment