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.
CodePudding user response:
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"); });
}
CodePudding user response:
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();
});
}
CodePudding user response:
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()
.
CodePudding user response:
No, you can't. promise.then()
returns a new promise, the original promise
cannot get a reference for that (may be multiple and may be none, it's like a tree).
Instead you can provide console.log("then hit")
to getPromise()
as a callback, which is used during create the promise.
function getPromise(cb) {
let p = new Promise((resolve, reject) => {
//some logical
resolve();
});
p.then(cb).finally(()=>{
//I want do something when outside then finished!
console.log("finally hit");
});
return p;
}
function doPromise() {
getPromise(data => { console.log("then hit"); });
}
doPromise()