Why promise fires function immediately? [duplicate] - javascript

This question already has answers here:
When is the body of a Promise executed?
(4 answers)
Why do promises execute at the point of declaration?
(2 answers)
Why does my Promise definition gets executed?
(2 answers)
Is the Promise constructor callback executed asynchronously?
(2 answers)
Closed 8 months ago.
I can't get why function in new Promise fires immediately. Shouldn't it be put in Microtask queue and fire after all global code has executed?
Code:
const prom = new Promise((resolve, reject) => {
console.log("in Promise");
resolve(20);
});
prom.then((data) => {
console.log(12312323);
console.log(data);
});
console.log(77);
Link to code
Output:
in Promise
77
12312323
20

When you construct a Promise, its task begins execution immediately.
const p = new Promise((resolve) => {
console.log('in promise');
resolve("value");
})
Promises are primarily useful for asynchronous tasks like network requests, and their delayed resolution can make it seem like the execution itself has been deferred, but that's not what's happening.
In this example you can see that there can be a significant delay between when the task starts and when the promise is resolved:
const p = new Promise((resolve) => {
console.log('first: in promise'); // first
setTimeout(() => resolve('resolved value'), 2000) // wait 2 seconds before resolving.
})
p.then(val => console.log(`third: ${val}`)); // third
console.log("second: after p.then"); // second

Related

JS - Why code does not run after async / await for promise [duplicate]

This question already has answers here:
Why does nodejs stop execution of while true loop inside async function
(3 answers)
Closed 28 days ago.
I have a sample code on TS playground represents my problem.
In an async function, I log the result after await for the promise, but only the code inside promise run, not the log outside of it. Could someone explain this problem?
Here is the code:
const asyncFnc = async () => {
let result = false;
await new Promise(resolve => {
setTimeout(() => {
// This log worked
console.log('waited 5s');
result = true;
}, 5000);
});
// This log did not worked
console.log(result);
}
asyncFnc();
And the result:
await sends the parent function to sleep until the promise on the right hand side settles (i.e. resolves or rejects).
Your promise never resolves or rejects. (i.e. you don't call resolve, make use of the second argument, or throw an exception).
Thus the parent function sleeps forever.
The idiomatic way to write this would be to avoid setting variables in the wider scope as a side effect, and just resolve with the values instead.
const asyncFnc = async () => {
const result = await new Promise(resolve => {
setTimeout(() => {
console.log('waited 5s');
resolve(true);
}, 5000);
});
console.log(result);
}
asyncFnc();
You need to call resolve() in your timeout

Why javascript promise returns during just the initiation phase? [duplicate]

This question already has answers here:
Is the Promise constructor callback executed asynchronously?
(2 answers)
When is the body of a Promise executed?
(4 answers)
Closed 5 months ago.
I was reading into javascript promises in depth. I came across one fundamental issue with my understanding.
Here is the piece of code :
let p = new Promise(function (resolve, reject) {
let a = true
if (a) {
resolve(console.log("a was true"));
} else reject("a was false")
})
Why the above piece of code immediately logs an a was true even if I haven't called it as such:
p.then((msg) => {
return msg
})
However,The following piece of code only logs the value with .then() calls
let p = new Promise(function (resolve, reject) {
let a = true
if (a) {
resolve("a was true")
} else reject("a was false")
})
p.then((msg) => {
console.log(msg)
}).catch((msg) => {
console.log(msg)
})
If someone can point out, why the very first piece of code doesnt need a .then() chain and does an early logs?
Please Note, I understand this is not async code, its for demo purpose only.
The promise executor is executed immediately, even if you don't .then the promise.
Your first code is equivalent to
let p = new Promise(function (resolve, reject) {
let a = true
if (a) {
let value = console.log('a was true');
resolve(value);
} else reject('a was false')
})
and as you know, console.log() logs the string as a side effect and returns undefined, so the resolved value of that promise is undefined.
In your second example, the resolved value of the promise is the string "a was true", and nothing is logged as a side effect.

JS: awaiting promises in map [duplicate]

This question already has answers here:
Resolve promises one after another (i.e. in sequence)?
(36 answers)
Is Node.js native Promise.all processing in parallel or sequentially?
(14 answers)
Closed 6 months ago.
I asked a question that was closed due to similar questions but even after reading those and seeing that map is not Promise aware, I have tried to use await Promise.all() around my mapping.
let foo = [1,2,3];
(async() => {
await Promise.all(foo.map(x => {
return new Promise(async function(resolve) {
await setTimeout(() => {
console.log("X")
resolve()
}, 3000)
});
}))
})()
instead of sequentially getting a "X" log every 3 seconds, it's just waiting 3 seconds and then logging them all. I am not sure what I am doing wrong at this point.
You are setting all the timeouts together at once. You need to increase the timeout duration in each iteration, maybe like this:
let foo = [1,2,3];
(async() => {
await Promise.all(foo.map((x, i) => {
return new Promise(async function(resolve) {
await setTimeout(() => {
console.log("X")
resolve()
}, 3000 * (i + 1))
});
}))
})()

Can't get .then to happen after promised timeout is finished in JavaScript [duplicate]

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
How can I pass a parameter to a function without it running right away?
(3 answers)
Closed last year.
Hey, i am trying to return this console after 1000 milli sec using this promise, but for some reason it consoles before ending the setTime out. Any idea how I can get the console.log to happen after the timeOutPromise is finished?
const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });
const thisPromise = (num1, num2) => new Promise((resolve, reject) => {
timeOutPromise()
.then(resolve(console.log(num1 + num2)))
.catch(reject(Error));
});
thisPromise(1, 2);
Your code is calling console.log synchronously when the promise is set up. You need to pass a callback to then, not the result of console.log(). Further, if you already have a promise, no need to wrap it in a promise constructor, just use chaining.
const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });
const thisPromise = (num1, num2) => timeOutPromise()
.then(() => console.log(num1 + num2))
thisPromise(1, 2);

Use await only for 20 seconds [duplicate]

This question already has answers here:
NodeJS Timeout a Promise if failed to complete in time
(8 answers)
Closed 2 years ago.
I am waiting for my promise to resolve in an async function using await but I want to wait for only 20 sec. If no response comes in that time (neither positive nor negative from the promise), I want to continue and display 'timeout'. How can I do this?
You can use Promise.race:
const promise1 = func();
const promise2 = new Promise((res, rej) => setTimeout(rej, 20000));
try {
await Promise.race([promise1, promise2]);
} catch (e) {
// time out or func failed
}

Categories