In general, you don't get access to the current promise inside the .then()
handler. And, for the most part, you couldn't do anything useful anyway. Adding another .then()
handler does not do anything different than the .then()
handler you're already in. Once fulfilled, promises never change their state.
If you want to repeat something, you make a function out of the thing you want to repeat and you call it over again from within the .then()
handler and you return the resulting promise (thus chaining it to the previous promise).
Here's an example:
// utility delay function that returns a promise
function delay(t, val) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(val);
}, t);
});
}
// repeatedly call someAsyncOp() until we see the operation is finished
function repeatUntil(t) {
return someAsyncOp().then(function(state) {
if (state !== "finish") {
return delay(t).then(repeatUntil);
}
});
}
// sample usage
repeatUntil(5000).then(function() {
// state is finished here
}).catch(function(err) {
// error here
});