Here is the code.
function getPromise():Promise<any> {
let p = new Promise<any>((resolve, reject) => {
//some logical
resolve(data);
});
p.finally(()=>{
//I want do something when outside then finished!
console.log("finally hit");
});
return p;
}
function doPromise():void {
a.getPromise().then(data => { console.log("then hit"); });
}
But the finally runs before then. So how can I do something after outside then.
I do not want to add finally after then, because the promise called many places. so I want do it in one place.
Maybe you can incorporate callback into getPromise?
function getPromise(callback):Promise<any> {
let p = new Promise<any>((resolve, reject) => {
//some logical
resolve(data);
});
p.then(callback)
p.finally(()=>{
//I want do something when outside then finished!
console.log("finally hit");
});
return p;
}
function doPromise():void {
getPromise(data => { console.log("then hit"); });
}
What you have to do is retrun a callback which you can use later on like this:
type GetPromise = {
p: Promise<any>;
finalCallback: () => void;
}
function getPromise():GetPromise {
let p = new Promise<any>((resolve, reject) => {
//some logical
resolve(data);
});
finalCallback(()=>{
//I want do something when outside then finished!
console.log("finally hit");
});
return {p, finalCallback};
}
function doPromise():void {
const {p: promise, finalCallback} = getPromise()
promise().then(data => {
console.log("then hit");
finalCallback();
});
}
Your getPromise() its a Promise itself, so your .then() will run only after it concludes, in this case, after the .finally().
You can put the .then() inside of getPromise() or move the .finally() to the outside after the .then().