It appears that the promises are running as soon as declared in the array and not when promise.all is called.
p1 = new Promise(function (resolve, reject) {
console.log('running geek1');
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < 2000);
resolve('timeout geek1');
});
p3 = new Promise(function (resolve, reject) {
console.log('running geek3');
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < 2000);
resolve('geek3');
});
p4 = function () {
return new Promise(function (resolve, reject) {
console.log('running geek4');
resolve('geek4');
});
}
p5 = new Promise(function (resolve, reject) {
console.log('running geek5');
resolve('geek5');
});
When you run it notice the delay I put it pauses the execution of the javascript. Which means to me this is running the code inside the promise as soon as I declare it.
results are:
running geek1
running geek3
running geek5
notice it doesn’t run p4 cause I returned the promise so it wouldn’t execute immediately.
But if I add
Promise.all([p1, p4, p5, p3]).then(function (values) {
console.log(values);
});
I get the following out
running geek1
running geek3
running geek5
['timeout geek1', [Function: p4], 'geek5', 'geek3']
Notice that p4 did not run under promise.all and returned the value as a function.
How do I create a dynamic array of promises to run them under Promise.all?
I find conflicting examples on technique. It doesn’t make sense why I need to do return new promise to make sure it doesn’t run on declaration. It is a constructor and I am passing in a function definition. So why is it running?
If I did the following:
class SampleClass {
constructor(testFunc, value) {
this.testFunc = testFunc;
this.value = value;
}
writeIt(){
console.log(this.testFunc(this.value));
}
}
console.log("declare");
let sc = new SampleClass((value) => { console.log(value); value++; console.log(value); return "added value" }, 453);
console.log("between");
sc.writeIt();
it works as I expect it the values don’t get written until I call writeIt()
this is what it returns.
declare
between
453
454
added value
Help is greatly appreciated.