Reputation: 457
I'm trying to implement Promise statements in my code and would love some help. I have a function that runs with a setTimeout. I want to call a function once that is completed.
Tried including Promise statements, but I have a feeling I'm not doing it correctly. Any feedback is helpful
function App(){
let exampleProm = new Promise(
function(){
type.type("hello , dexter", 100);
}
).then(console.log('finished'));
}
App();
//code that gets called first
module.exports = {
type: function(phrase, delaySpeed){
let total = 0;
let empty = [];
for(let i = 0; i < phrase.length;i++){
total += delaySpeed;
setTimeout(() => {
empty.push(phrase.charAt(i));
process.stdout.write(chalk.blue.bold(empty[i]));
if(empty.length === phrase.length){ //if complete
process.stdout.write('\n'); //puts on separate line
}
},total);
}
}
}
Upvotes: 0
Views: 87
Reputation: 171700
Use an array of promises that each resolve() inside the setTimeout()
and then Promise.all()
to run the code after they have all resolved
module.exports = {
type: function(phrase, delaySpeed) {
let total = 0;
let empty = [];
let promises = []
for (let i = 0; i < phrase.length; i++) {
total += delaySpeed;
// new promise for each character
let promise = new Promise(function(resolve, reject) {
setTimeout(() => {
empty.push(phrase.charAt(i));
process.stdout.write(chalk.blue.bold(empty[i]));
if (empty.length === phrase.length) { //if complete
process.stdout.write('\n'); //puts on separate line
}
// assuming above writes are synchronous can now resolve promise
resolve()
}, total);
});
// push new promise to array
promises.push(promise)
}
// return the all() promise
return Promise.all(promises)// add another then() if you need to return something to next then() in App()
}
}
function App(){
type.type("hello , dexter", 100).then(function(){
// this then() fires when the Promise.all() resolves
console.log('finished')
});
}
Upvotes: 2
Reputation: 735
The reason your .then
handler never gets called is because the promise is stuck in its initial state, which is "pending".
Promises can be pending or settled (fulfilled / rejected). The callback passed to a Promise constructor takes two params, resolve
(trigger a fulfill) and reject
(trigger a rejection).
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
Check out the source for the code above at the MDN docs for the Promise API.
I reckon the example above gives you a hint on how to implement promise based delays, but if you need further assistance, let me know.
Upvotes: 1