Thursday, February 28, 2019

asynchronous - Javascript Promise and Async code



I'm struggling to wrap my head around the concept of async and promises in js. I can't figure out why the code below doesn't print anything on my console.




I'm assuming it's because the code inside my Promise is not asynchronous, but isn't that the point of a promise: to make something synchronous become asynchronous?



If that's not the case, how could I truly "transform" a sync code into async without using any built in js functions (setTimeOut,etc)?



function countdown(seconds) {
return new Promise(function(resolve, reject) {
for (let i = seconds; i >= 0; i--) {
if (i > 0) console.log(i + '...');
else resolve(console.log("GO!"));
}

}
};
count = countdown(5).then(() => console.log('Completed'), (err) => console.log(err.message));

Answer




how could I truly "transform" a sync code into async without using any built in js functions (setTimeOut,etc)?




By it's nature, javascript code is synchronous (waits for howls of protest to abate) ...




Every (non-native) function that is asynchronous is due to that function, either




  1. directly calling one of those native asynchronous functions, or

  2. calling other functions that call functions etc that eventually call one of these asynchronous functions directly



the only way to transform some code from synchronous to asynchronous is to use one of the many "native" functions that are asynchronous in nature (again, either directly, or indirectly via other functions that eventually will have to call one of these asynchronous functions directly)


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...