Created
July 27, 2017 01:43
-
-
Save lisp-ceo/a5de91aac50b8b3b0254cee56f3615ed to your computer and use it in GitHub Desktop.
Synchronous execution of asynchronous function using async/await
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
#!/usr/bin/env node | |
let success = 'success'; | |
let failure = 'failure'; | |
var callCount = 0; | |
async function runSyncAsync() { | |
console.log('runSyncAsync'); | |
let resCallCount = 0; | |
let success = 4; | |
while (resCallCount != undefined && resCallCount < 4) { | |
resCallCount = await run(); | |
} | |
return success == resCallCount; | |
// return [r1,r2,r3,r4]; // Important! Otherwise it will return some bizarre object | |
// { '0': {}, | |
// '1': | |
// { [Function: require] | |
// resolve: [Function: resolve], | |
// main: | |
// Module { | |
// id: '.', | |
// exports: {}, | |
// parent: null, | |
// filename: '/Users/htmldrum/code/javascript/engine.js', | |
// loaded: true, | |
// children: [], | |
// paths: [Array] }, | |
// extensions: { '.js': [Function], '.json': [Function], '.node': [Function] }, | |
// cache: { '/Users/htmldrum/code/javascript/engine.js': [Object] } }, | |
// '2': | |
// Module { | |
// id: '.', | |
// exports: {}, | |
// parent: null, | |
// filename: '/Users/htmldrum/code/javascript/engine.js', | |
// loaded: true, | |
// children: [], | |
// paths: | |
// [ '/Users/htmldrum/code/javascript/node_modules', | |
// '/Users/htmldrum/code/node_modules', | |
// '/Users/htmldrum/node_modules', | |
// '/Users/node_modules', | |
// '/node_modules' ] }, | |
// '3': '/Users/htmldrum/code/javascript/engine.js', | |
// '4': '/Users/htmldrum/code/javascript' } | |
}; | |
function run() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
callcbSucc(resolve); | |
}, 500); | |
}); | |
} | |
function callcbSucc(fn) { | |
callCount++; | |
console.log("callCount: ", callCount); | |
fn(callCount); | |
} | |
function callcbFail(fn) { | |
fn(failure); | |
} | |
runSyncAsync() | |
.then(x => { | |
console.log("Resolved with: ", x); | |
}).catch(reason => { | |
console.log("Failed with reason: ", reason); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With promises