Skip to content

Instantly share code, notes, and snippets.

@gitSambhal
Created December 10, 2023 08:48
Show Gist options
  • Save gitSambhal/3301803ee69c85f370b4403802ff056c to your computer and use it in GitHub Desktop.
Save gitSambhal/3301803ee69c85f370b4403802ff056c to your computer and use it in GitHub Desktop.
Nodejs Tutorial - Convert Async functions into Sync functions
const deasync = require('deasync')
const axios = require('axios')
const cp = require('child_process');
function promiseToSync(func) {
let isDone = false;
let resp
func().then(data => {
isDone = true;
resp = data
})
deasync.loopWhile(() => !isDone)
return resp;
}
function callbackToSync(func) {
return deasync(func)
}
const log = console.log;
console.log = function () {
log.apply(console, [new Date(), ...arguments]);
};
const getData = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/todos/1')
return data
}
function myPromise(duration = 1) {
// Use the new keyword when calling the Promise constructor
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise resolved"), duration * 1000);
});
}
const data = promiseToSync(myPromise)
console.log('πŸš€ ~ file: index.js:34 ~ data:', data);
const data2 = promiseToSync(getData)
console.log('πŸš€ ~ file: index.js:36 ~ data2:', data2);
const data3 = promiseToSync(() => myPromise(3))
console.log('πŸš€ ~ file: index.js:38 ~ data3:', data3);
const exec = callbackToSync(cp.exec)
const resp1 = exec('node -v')
console.info(resp1);
const resp2 = exec('ls -la')
console.info(resp2);
const resp3 = exec('curl https://httpstat.us/200')
console.info(resp3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment