How to resolve promises one after another? - javascript

How could I fire off promises one after the other?
waitFor(t), is a function that returns a promise that resolves after t time. What I wish to be able to do with that is:
waitFor(1000) Then when finished, console.log('Finished wait of 1000 millis') then
waitFor(2000) Then when finished, console.log('Finished wait of 2000 millis') then
waitFor(3000) Then when finished, console.log('Finished wait of 3000 millis')
Here is what I tried:
waitFor(1000).then(function(resolve, reject) {
console.log(resolve);
}).then(waitFor(2000).then(function(resolve, reject) {
console.log(resolve);
})).then(waitFor(3000).then(function(resolve, reject) {
console.log(resolve);
}));
Unfortunately this console.logs the statements each 1 second after another, which means that the promises where all called at once.
I managed to fix this with callbacks like so, yet that makes everything very ugly:
waitFor(1000).then(function(resolve, reject) {
console.log(resolve+' # '+(new Date().getSeconds()));
waitFor(2000).then(function(resolve, reject) {
console.log(resolve+' # '+(new Date().getSeconds()));
waitFor(3000).then(function(resolve, reject) {
console.log(resolve+' # '+(new Date().getSeconds()));
});
});
});
So how should I do this with promises that makes it work, yet isn't using ugly callback hell?
Undesired result: http://jsfiddle.net/nxjd563r/1/
Desired result: http://jsfiddle.net/4xxps2cg/

I found your solution.
You need to have each then to return a new promise, so that the next then can react once the previous one has been resolved.
waitFor(1000).then(function(result) {
$('#result').append(result+' # '+(new Date().getSeconds())+'<br>');
return waitFor(2000);
}).then(function(result) {
$('#result').append(result+' # '+(new Date().getSeconds())+'<br>');
return waitFor(3000);
}).then(function(result) {
$('#result').append(result+' # '+(new Date().getSeconds())+'<br>');
});
jsfiddle http://jsfiddle.net/4xxps2cg/2/

You can put promises into array and use reduce to chain them, starting with one extra resolved promise.
function waitPromise(time) {
//console.log(time);
return new Promise( (resolve,reject) => {
setTimeout( () => {resolve('resolved');}, time);
});
}
function log(data) {
return new Promise( (resolve,reject) => {
console.log( data +' # '+(new Date().getSeconds()));
resolve();
});
}
var ps = [];
for (var i=0;i<3;i++) {
let time = (i+1) * 1000;
ps.push( () => waitPromise(time) );
ps.push( log );
}
console.log( 'started' +' # '+(new Date().getSeconds()));
var p = Promise.resolve();
ps.reduce( (p,c) => {return p.then(c)}, p);

The format for calling and waiting is a bit off, your then should be a function that returns a promise, since now you're passing a function call instead of a function, its running that request instantly instead of waiting to call the function as a result of the promise.
This should do it:
function waitFor(timeout) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(`Finished waiting ${timeout} milliseconds`);
}, timeout);
});
}
waitFor(1000).then(function(resolve, reject) {
$('#result').append(resolve+' # '+new Date().getSeconds()+'<br/>');
}).then(function(){
return waitFor(2000)
}).then(function(resolve, reject) {
$('#result').append(resolve+' # '+new Date().getSeconds()+'<br/>');
}).then(function() {
return waitFor(2000)
}).then(function(resolve, reject) {
$('#result').append(resolve+' # '+new Date().getSeconds()+'<br/>');
})

waitFor() appear to be called immediately at .then() ; try returning waitFor() from within .then() anonymous function.
Could alternatively create array of duration values , use Array.prototype.shift() to call waitFor with each duration value in succession , or pass parameter timeout to waitFor ; if same process called at each .then() , include process at .then() chained to Promise in waitFor ; call same function waitFor at .then() chained to initial waitFor() call
var t = [1000, 2000, 3000];
function waitFor(timeout) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("`Finished waiting ${timeout} milliseconds`");
}, timeout && t.shift() || t.shift());
}).then(function (data) {
$('#result').append(data + ' # ' + new Date().getSeconds() + '<br/>');
})
}
waitFor().then(waitFor).then(waitFor)
//.then(function() {return waitFor(5000)})

Related

How to add a delay between recursions while not breaking the promise chain? [duplicate]

Here i am trying to wrap my head around promises.Here on first request i fetch a set of links.and on next request i fetch the content of first link.But i want to make a delay before returning next promise object.So i use setTimeout on it. But it gives me the following JSON error (without setTimeout() it works just fine)
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data
i would like to know why it fails?
let globalObj={};
function getLinks(url){
return new Promise(function(resolve,reject){
let http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(http.readyState == 4){
if(http.status == 200){
resolve(http.response);
}else{
reject(new Error());
}
}
}
http.open("GET",url,true);
http.send();
});
}
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
setTimeout(function(){
return getLinks(globalObj["two"]+".txt"); // without setTimeout it works fine
},1000);
});
To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(resolve => setTimeout(resolve, t, v));
}
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
Here you're returning a promise from the .then() handler and thus it is chained appropriately.
You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:
function delay(t, v) {
return new Promise(resolve => setTimeout(resolve, t, v));
}
Promise.prototype.delay = function(t) {
return this.then(function(v) {
return delay(t, v);
});
}
Promise.resolve("hello").delay(500).then(function(v) {
console.log(v);
});
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
The shorter ES6 version of the answer:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
And then you can do:
delay(3000).then(() => console.log('Hello'));
If you are inside a .then() block and you want to execute a settimeout()
.then(() => {
console.log('wait for 10 seconds . . . . ');
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log('10 seconds Timer expired!!!');
resolve();
}, 10000)
});
})
.then(() => {
console.log('promise resolved!!!');
})
output will as shown below
wait for 10 seconds . . . .
10 seconds Timer expired!!!
promise resolved!!!
Happy Coding!
Since node v15, you can use timers promise API
example from the doc:
import { setTimeout } from 'timers/promises'
const res = await setTimeout(100, 'result')
console.log(res) // Prints 'result'
In node.js you can also do the following:
const { promisify } = require('util')
const delay = promisify(setTimeout)
delay(1000).then(() => console.log('hello'))
For the current LTS its easier and we can use async/await to handle timeouts. Please note that this is the recommended way to use timeout nowadays.
Thenables is not the recommended way.
const { promisify } = require('util')
const sleep = promisify(setTimeout)
async function myFunction() {
await sleep(1e3)
console.log('This will be seen after 1 sec')
await sleep(5e3)
console.log('This will be seen after 5 sec after')
}
const myStuff = new Promise(function (resolve) {
console.log("before timeout");
setTimeout(
function (x) {
console.log("inside the timeout");
resolve(x);
},
3000,
"after timeout"
);
}).then((response) => console.log(response));

ES6 why does one have to return a promise?

What's the difference between the two (without a return)
function doAsyncTask() {
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Async Work Complete");
if (error) {
reject();
} else {
resolve();
}
}, 1000);
});
return promise;
}
The following has no "Return Promise"
function doAsyncTask() {
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Async Work Complete");
if (error) {
reject();
} else {
resolve();
}
}, 1000);
});
}
As an extension to Quentin's answer, you should return a promise always.
Idea is, if a function is an async function, it should provide a way to listen to changes. Its upon caller to decide if they need to react to changes.
So you can call your function as:
doAsyncTask().then(...);
or just
doAsyncTask();
But if we do not return promise, caller will never have an option to llisten.
ES6 why does one have to return a promise?
You don't.
What's the difference between the two (without a return)
The difference is that one doesn't return anything.
(So you can't call doAsyncTask and make use of the return value).
var doAsyncTask1 = function() {
var promise = new Promise(resolve => {
/// task that takes 5 seconds
setTimeout(resolve, 5000);
});
return promise;
}
var doAsyncTask2 = function() {
var promise = new Promise(resolve => {
/// task that takes 5 seconds
setTimeout(resolve, 5000);
});
// no return
}
await doAsyncTask1();
console.log('task complete'); // this line of code runs 5 seconds after the previous one
await doAsyncTask2(); // because you have returned nothing, 'await' does nothing
console.log('task2 not complete yet'); // this line of code runs immediately after the previous one, before the 5-second task is complete

Promises - How to make asynchronous code execute synchronous without async / await?

var p1 = new Promise(function(resolve, reject) {
setTimeout(() => resolve("first"), 5000);
});
var p2 = new Promise(function(resolve, reject) {
setTimeout(() => resolve("second"), 2000);
});
var p3 = new Promise(function(resolve, reject) {
setTimeout(() => resolve("third"), 1000);
});
console.log("last to print");
p1.then(()=>p2).then(()=>p3).then(()=> console.log("last to be printed"))
As I was reading about promises, I know that I can print promises synchronous (in this case print: first, second, third, last to print) when I use async /await. Now I have also been reading that the same thing can be achieved using .then chaining and async/await is nothing 'special'. When I try to chain my promises, however, nothing happens except for the console.log of "last to be printed". Any insight would be great! Thanks!!
Edit to question:
var p1 = new Promise(function (resolve, reject) {
setTimeout(() => console.log("first"), 5000);
resolve("first resolved")
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(() => console.log("second"), 2000);
resolve("second resolved")
});
var p3 = new Promise(function (resolve, reject) {
setTimeout(() => console.log("third"), 0);
resolve("third resolved")
});
console.log("starting");
p1.then((val) => {
console.log("(1)", val)
return p2
}).then((val) => {
console.log("(2)", val)
return p3
}).then((val) => {
console.log("(3)", val)
})
Loggs:
starting
(1) first resolved
(2) second resolved
(3) third resolved
third
second
first
1: if executor function passed to new Promise is executed immediately, before the new promise is returned, then why are here promises resolved ()synchronously) first and after the setTimeouts (asynchronously) gets executed?
Return value vs. resolve promise:
var sync = function () {
return new Promise(function(resolve, reject){
setTimeout(()=> {
console.log("start")
resolve("hello") //--works
// return "hello" //--> doesnt do anything
}, 3000);
})
}
sync().then((val)=> console.log("val", val))
The executor function you pass to new Promise is executed immediately, before the new promise is returned. So when you do:
var p1 = new Promise(function(resolve, reject) {
setTimeout(() => resolve("first"), 5000);
});
...by the time the promise is assigned to p1, the setTimeout has already been called and scheduled the callback for five seconds later. That callback happens whether you listen for the resolution of the promise or not, and it happens whether you listen for resolution via the await keyword or the then method.
So your code starts three setTimeouts immediately, and then starts waiting for the first promise's resolution, and only then waiting for the second promise's resolution (it'll already be resolved, so that's almost immediate), and then waiting for the third (same again).
To have your code execute those setTimeout calls only sequentially when the previous timeout has completed, you have to not create the new promise until the previous promise resolves (using shorter timeouts to avoid lots of waiting):
console.log("starting");
new Promise(function(resolve, reject) {
setTimeout(() => resolve("first"), 1000);
})
.then(result => {
console.log("(1) got " + result);
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("second"), 500);
});
})
.then(result => {
console.log("(2) got " + result);
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("third"), 100);
});
})
.then(result => {
console.log("(3) got " + result);
console.log("last to print");
});
Remember that a promise doesn't do anything, and doesn't change the nature of the code in the promise executor. All a promise does is provide a means of observing the result of something (with really handy combinable semantics).
Let's factor out the common parts of those three promises into a function:
function delay(ms, ...args) {
return new Promise(resolve => {
setTimeout(resolve, ms, ...args);
});
}
Then the code becomes a bit clearer:
function delay(ms, ...args) {
return new Promise(resolve => {
setTimeout(resolve, ms, ...args);
});
}
console.log("starting");
delay(1000, "first")
.then(result => {
console.log("(1) got " + result);
return delay(500, "second");
})
.then(result => {
console.log("(2) got " + result);
return delay(100, "third");
})
.then(result => {
console.log("(3) got " + result);
console.log("last to print");
});
Now, let's put that in an async function and use await:
function delay(ms, ...args) {
return new Promise(resolve => {
setTimeout(resolve, ms, ...args);
});
}
(async() => {
console.log("starting");
console.log("(1) got " + await delay(1000, "first"));
console.log("(2) got " + await delay(500, "second"));
console.log("(3) got " + await delay(100, "third"));
console.log("last to print");
})();
Promises make that syntax possible, by standardizing how we observe asynchronous processes.
Re your edit:
1: if executor function passed to new Promise is executed immediately, before the new promise is returned, then why are here promises resolved ()synchronously) first and after the setTimeouts (asynchronously) gets executed?
There are two parts to that question:
A) "...why are here promises resolved ()synchronously) first..."
B) "...why are here promises resolved...after the setTimeouts (asynchronously) gets executed"
The answer to (A) is: Although you resolve them synchronously, then always calls its callback asynchronously. It's one of the guarantees promises provide. You're resolving p1 (in that edit) before the executor function returns. But the way you're observing the resolutions ensures that you observe the resolutions in order, because you don't start observing p2 until p1 has resolved, and then you don't start observing p3 until p2 is resolved.
The answer to (B) is: They don't, you're resolving them synchronously, and then observing those resolutions asynchronously, and since they're already resolved that happens very quickly; later, the timer callbacks run. Let's look at how you create p1 in that edit:
var p1 = new Promise(function (resolve, reject) {
setTimeout(() => console.log("first"), 5000);
resolve("first resolved")
});
What happens there is:
new Promise gets called
It calls the executor function
The executor function calls setTimeout to schedule a callback
You immediately resolve the promise with "first resolved"
new Promise returns and the resolved promise is assigned to p1
Later, the timeout occurs and you output "first" to the console
Then later you do:
p1.then((val) => {
console.log("(1)", val)
return p2
})
// ...
Since then always calls its callback asynchronously, that happens asynchronously — but very soon, because the promise is already resolved.
So when you run that code, you see all three promises resolve before the first setTimeout callback occurs — because the promises aren't waiting for the setTimeout callback to occur.
You may be wondering why you see your final then callback run before you see "third" in the console, since both the promise resolutions and the console.log("third") are happening asynchronously but very soon (since it's a setTimeout(..., 0) and the promises are all pre-resolved): The answer is that promise resolutions are microtasks and setTimeout calls are macrotasks (or just "tasks"). All of the microtasks a task schedules are run as soon as that task finishes (and any microtasks that they schedule are then executed as well), before the next task is taken from the task queue. So the task running your script does this:
Schedules a task for the setTimeout callback
Schedules a microtask to call p1's then callback
When the task ends, its microtasks are processed:
The first then handler is run, scheduling a microtask to run the second then handler
The second then handler runs and schedules a micro task to call the third then handler
Etc. until all the then handlers have run
The next task is picked up from the task queue. It's probably the setTimeout callback for p3, so it gets run and "third" appears in the console
Return value vs. resolve promise:
The part you've put in the question doesn't make sense to me, but your comment on this does:
I read that returning a value or resolving a promise is same...
What you've probably read is that returning a value from then or catch is the same as returning a resolved promise from then or catch. That's because then and catch create and return new promises when they're called, and if their callbacks return a simple (non-promise) value, they resolve the promise they create with that value; if the callback returns a promise, they resolve or reject the promise they created based on whether that promise resolves or rejects.
So for instance:
.then(() => {
return 42;
})
and
.then(() => {
return new Promise(resolve => resolve(42));
})
have the same end result (but the second one is less efficient).
Within a then or catch callback:
Returning a non-promise resolves the promise then/catch created with that value
Throwing an error (throw ...) rejects that promise with the value you throw
Returning a promise makes then/catch's promise resolve or reject based on the promise the callback returns
You cannot make asynchronous code execute synchronously.
Even async / await are just syntax that gives you a synchronous-style control flow inside a promise.
When I try to chain my promises, however, nothing happens except for the console.log of "last to be printed". Any insight would be great!
The other functions don't generate any output. That has nothing to do with them being in promises.
You start three timers (all at the same time), then log 'last to print', then chain some promises so that 'last to be printed' will print when all three promises resolve (5 seconds after you start them all going).
If you want the timers to run sequentially, then you have to initiate them only when the previous one has finished, and if you want to see what they resolve with then you have to write code that actually looks at that.
function p1() {
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("first"), 5000);
});
}
function p2() {
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("second"), 2000);
});
}
function p3() {
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("third"), 1000);
});
}
function log(value) {
console.log("Previous promise resolved with " + value);
}
p1()
.then(log)
.then(p2)
.then(log)
.then(p3)
.then(log)
.then(() => console.log("last to be printed"));
Async/await is, arguably, neater:
function p1() {
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("first"), 5000);
});
}
function p2() {
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("second"), 2000);
});
}
function p3() {
return new Promise(function(resolve, reject) {
setTimeout(() => resolve("third"), 1000);
});
}
function log(value) {
console.log("Previous promise resolved with " + value);
}
(async function() {
log(await p1());
log(await p2());
log(await p3());
console.log("last to be printed");
}());
If you need to call an await but the function that contains that await doesn't have to be async, because you need, for example, a "number" and not a "Promise number ", you can do de next:
var ex: number = new Number(async resolve => {
var f = await funcionExample();
resolve(f);
}).valueOf();

Using setTimeout on promise chain

Here i am trying to wrap my head around promises.Here on first request i fetch a set of links.and on next request i fetch the content of first link.But i want to make a delay before returning next promise object.So i use setTimeout on it. But it gives me the following JSON error (without setTimeout() it works just fine)
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data
i would like to know why it fails?
let globalObj={};
function getLinks(url){
return new Promise(function(resolve,reject){
let http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(http.readyState == 4){
if(http.status == 200){
resolve(http.response);
}else{
reject(new Error());
}
}
}
http.open("GET",url,true);
http.send();
});
}
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
setTimeout(function(){
return getLinks(globalObj["two"]+".txt"); // without setTimeout it works fine
},1000);
});
To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(resolve => setTimeout(resolve, t, v));
}
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
Here you're returning a promise from the .then() handler and thus it is chained appropriately.
You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:
function delay(t, v) {
return new Promise(resolve => setTimeout(resolve, t, v));
}
Promise.prototype.delay = function(t) {
return this.then(function(v) {
return delay(t, v);
});
}
Promise.resolve("hello").delay(500).then(function(v) {
console.log(v);
});
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
The shorter ES6 version of the answer:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
And then you can do:
delay(3000).then(() => console.log('Hello'));
If you are inside a .then() block and you want to execute a settimeout()
.then(() => {
console.log('wait for 10 seconds . . . . ');
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log('10 seconds Timer expired!!!');
resolve();
}, 10000)
});
})
.then(() => {
console.log('promise resolved!!!');
})
output will as shown below
wait for 10 seconds . . . .
10 seconds Timer expired!!!
promise resolved!!!
Happy Coding!
Since node v15, you can use timers promise API
example from the doc:
import { setTimeout } from 'timers/promises'
const res = await setTimeout(100, 'result')
console.log(res) // Prints 'result'
In node.js you can also do the following:
const { promisify } = require('util')
const delay = promisify(setTimeout)
delay(1000).then(() => console.log('hello'))
For the current LTS its easier and we can use async/await to handle timeouts. Please note that this is the recommended way to use timeout nowadays.
Thenables is not the recommended way.
const { promisify } = require('util')
const sleep = promisify(setTimeout)
async function myFunction() {
await sleep(1e3)
console.log('This will be seen after 1 sec')
await sleep(5e3)
console.log('This will be seen after 5 sec after')
}
const myStuff = new Promise(function (resolve) {
console.log("before timeout");
setTimeout(
function (x) {
console.log("inside the timeout");
resolve(x);
},
3000,
"after timeout"
);
}).then((response) => console.log(response));

Understanding .then() ES6

I ran into a bug in my code that puzzled me for a long time and am looking for some clarification.
In this code, the commented out inner promise was causing a problem. The Promise.all() at the end was continuing as soon as the setTimeout hit, not after the resolve inside the timeout.
Wrapping the async code with a promise fixes the flow problem, but why is this?
Essentially, why can't we just run normal async code in a .then() chain, an return a Promise.resolve() at the end of the async callback?
var asyncPromise = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('Async Promise done');
resolve();
}, 1000);
});
};
var generateSignupPromises = function(qty) {
var promiseArray = [];
for (var i = 1; i <= qty; i++) {
promiseArray.push(
function() {
return asyncPromise()
.then(function() {
console.log('Before Timeout');
//Uncommenting this fixes the issue
//return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('After Timeout');
//resolve();
return Promise.resolve();
}, 500);
//})
});
}
);
}
return promiseArray;
};
var test = generateSignupPromises(1);
Promise.all([test[0]()])
.then(function() {
console.log('Done');
});
Link to running code: http://www.es6fiddle.net/imfdtuxc/
why can't we just run normal async code in a .then() chain, an return a Promise.resolve() at the end of the async callback?
You perfectly can. But any value - be it a promise or whatever - being returned from a plain asynchronous callback is just ignored as usual.
There is nothing that starting the asynchronous action inside a then callback changes about this, setTimeout just doesn't return a promise - and the then won't know about anything asynchronous happening that it could wait for.
If you want to return a promise from a callback and get another promise for that eventual result, it has to be a then callback:
asyncPromise()
.then(function() {
return new Promise(function(resolve, reject) {
// ^^^^^^
setTimeout(resolve, 500);
}).then(function() {
// ^^^^^^^^^^^^^^^
return Promise.resolve();
});
});
Then is a sync function so if you want to do async task inside then, you has to return a Promise.
Also, Promise.all expect an array of promises. Not an array of an array.
var asyncPromise = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('Async Promise done');
resolve();
}, 1000);
});
};
var generateSignupPromises = function(qty) {
var promiseArray = [];
for (var i = 1; i <= qty; i++) {
promiseArray.push(
function() {
return asyncPromise()
.then(function() {
console.log('Before Timeout');
//Uncommenting this fixes the issue
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('After Timeout');
resolve();
//return Promise.resolve();
}, 500);
})
});
}
);
}
return promiseArray;
};
var test = generateSignupPromises(1);
Promise.all([test[0]()])
.then(function() {
console.log('Done');
});
http://www.es6fiddle.net/imfe2sze/

Categories