I am new to JS/TS and thus Promises, I managed to write my "Steps" as promises from porting from C# but I will take whatever construct you can outline. (working with ionic2/TS).
Why Promises: I using Promises in TS in order to sequence a series of tasks during a playback of a slide in a collection of slides. (not sure I am using promises correctly, perhaps there is other constructs, patterns to consider for this, let me know)
My Goals: How do I construct a chain of promises such that:
- I can iterate over a chain of steps...
- I can repeat Step2() say 5 times?
- Recover from Step1() failure and continue with the next Index/Slide (all next steps).
Here is my current code outline
PlayAll() {
Step1(Index)
.then(() => {
console.log("PlayAll<<promise------------Step1 DONE");
Step2(i)
.then(() => {
console.log("PlayAll<<promise------------Step2 DONE");
if (Index < Count) {
Index++;
// tell slider to move and wait for its change event
// ???
}
else
// -) Report we are done with all Slides
// Perhaps I should write PlayAll as a promise too?
// instead of using a Callback ??
if (typeof (this.Done) == "function")
this.Done(); // a registered callback.
}
.catch(() => {
console.log("PlayAll<<promise------------Step2 FAIL");
}
.catch(() => {
console.log("PlayAll<<promise------------Step1 FAIL");
}
}
My Step1() looks like this
// Using Howler.js (makes audio work on Android)
// https://stackoverflow.com/questions/30069988/how-can-i-create-a-promise-for-the-end-of-playing-sound
// 20160820
PlayOne(Media: string) {
console.log("AudioPlayList------------>>PlayOne Media is", Media);
return new Promise((resolve, reject) => { // return a promise
var audio = new Howl({ src: [Media] }); // create audio wo/ src
// cache a class level copy for other methods, eg. pause
this.audio = audio;
//
// TODO: needs help:
// not sure how to code reject here ???
// does this look correct?
// audio.on('error', () => {
// console.log("AudioPlayList<<e------------audio ERROR");
// reject(Media);
// return reject;
// });
audio.on('end', () => {
console.log("AudioPlayList<<e------------audio ENDED");
resolve(Media);
return resolve;
}); // when done, resolve
audio.play();
});
}
My Step3() not shown in the above outline looks like this
timer1: any; // needed to abort Slide's PostPause, if user alters playback
// https://www.typescriptlang.org/docs/release-notes/typescript-1.7.html
// 20160812
private SlidePostPause() {
console.log("PlayAll------------>>PostPause");
return new Promise<void>(
resolve => {
this.timer1 = setTimeout(resolve, this.Model.PostPause * 1000);
});
}
This link How to return from a Promise's catch/then block
says _Returning a regular value from a reject handler, causes the next .then() resolve handler to be called (e.g. normal processing continues)_
which is what I typically want.
I have also read this link https://github.com/basarat/typescript-book/blob/master/docs/promise.md
but I am still lost :)
Please be as explicit as you can be.
Thank you for your help.