Created
July 25, 2019 12:41
-
-
Save bills-appworks/7ea02df64c879e2b6a1405c9f46e54d5 to your computer and use it in GitHub Desktop.
Promise/async/await for calling asynchronous API like synchronous
This file contains hidden or 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
'use strict'; | |
const start_time = Date.now(); | |
function timestamp_log(message) { | |
const duration = Date.now() - start_time; | |
console.log(`[${duration}]: ${message}`); | |
} | |
timestamp_log('script start'); | |
function callback_at_late(param, resolve, reject) { | |
timestamp_log('callback_at_late start'); | |
timestamp_log(`callback_at_late param: ${param}`); | |
timestamp_log('callback_at_late end'); | |
resolve(`callback_at_late(${param})`); | |
return; | |
} | |
function background_procedure(callback, param) { | |
timestamp_log('background_procedure start'); | |
const background_promise = new Promise(function(background_resolve, background_reject) { | |
setTimeout(callback, 3000, param, background_resolve, background_reject); | |
}); | |
timestamp_log('background_procedure end'); | |
return background_promise; | |
} | |
function foreground_procedure_01(param) { | |
timestamp_log('foreground_procedure_01 start'); | |
timestamp_log(`foreground_procedure_01 param: ${param}`); | |
timestamp_log('foreground_procedure_01 end'); | |
} | |
function foreground_procedure_02(param) { | |
timestamp_log('foreground_procedure_02 start'); | |
timestamp_log(`foreground_procedure_02 param: ${param}`); | |
timestamp_log('foreground_procedure_02 end'); | |
} | |
function foreground_procedure_03(param) { | |
timestamp_log('foreground_procedure_03 start'); | |
timestamp_log(`foreground_procedure_03 param: ${param}`); | |
timestamp_log('foreground_procedure_03 end'); | |
} | |
function foreground_procedure_04(param) { | |
timestamp_log('foreground_procedure_04 start'); | |
timestamp_log(`foreground_procedure_04 param: ${param}`); | |
timestamp_log('foreground_procedure_04 end'); | |
} | |
async function subroutine() { | |
timestamp_log('subroutine start'); | |
const background_result = await background_procedure(callback_at_late, 'BACKGROUND'); | |
timestamp_log('background_promise'); | |
foreground_procedure_01(background_result); | |
foreground_procedure_02(background_result); | |
timestamp_log('subroutine end'); | |
return `subroutine(${background_result})`; | |
} | |
async function main() { | |
timestamp_log('main start'); | |
const subroutine_result = await subroutine(); | |
foreground_procedure_03(subroutine_result); | |
foreground_procedure_04(subroutine_result); | |
timestamp_log('main end'); | |
} | |
main(); | |
timestamp_log('script end'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment