user3682983
user3682983

Reputation: 177

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));

Upvotes: 0

Views: 165

Answers (2)

Jaromanda X
Jaromanda X

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

  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)

Upvotes: 2

Abdennour TOUMI
Abdennour TOUMI

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

Related Questions