Reputation: 177
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));
Upvotes: 0
Views: 165
Reputation: 1
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
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)
Upvotes: 2
Reputation: 93531
It is missing )
, and it works now after adding that parenthesis .. Run snippet to check
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!"));
}
}) // <---⚠️ I mean this parenthesis
};
count = countdown(5).then(() => console.log('Completed'), (err) => console.log(err.message));
Upvotes: 2