Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet:

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"); });
}

The issue here is that finally runs before then. How can I execute something after the outside then block?

I prefer not to add finally after each then statement due to multiple calls to the promise. Is there a way to handle this in a single place?

Answer №1

To create a callback that can be utilized later on, you need to follow these steps:

type PromiseCallback = {
  p: Promise<any>;
  finalCallback: () => void;
}
function createPromise(): PromiseCallback {
  let p = new Promise((resolve, reject) => {
      //perform some operations
      resolve(data);
  });
  finalCallback(()=>{ 
      //Do something after the promise is resolved
      console.log("Finally executed");
  });
  return {p, finalCallback};
}

function executePromise():void {
  const {p: promise, finalCallback} = createPromise()
  promise().then(data => { 
    console.log("Executed 'then' block");  
    finalCallback();
  });
}

Answer №2

Perhaps you could consider integrating a callback function into the getPromise method?


function getPromise(callback):Promise<any> {
    let p = new Promise<any>((resolve, reject) => {
        //perform some logic
        resolve(data);
    });
    p.then(callback)
    p.finally(()=>{ 
        //Execute code after then block completes 
        console.log("finally hit");
    });
    return p;
}

function doPromise():void {
    getPromise(data => { console.log("then hit"); });
}

Answer №3

When using your getPromise() function, keep in mind that it returns a Promise itself. This means that the code inside your .then() will only run once the promise has resolved, which in this case is after the .finally() block.

To organize your code better, you have the option to place the .then() within the getPromise() function or move the .finally() outside of it following the .then().

Answer №4

Sorry, it's not possible. When you use promise.then(), a new promise is returned, and the original promise cannot access it directly (it's like a tree structure).

Instead of trying to reference the new promise from the original one, you can pass console.log("then hit") as a callback to the getPromise() function when creating the promise.


function getPromise(cb) {
    let p = new Promise((resolve, reject) => {
        //some logic here
        resolve();
    });
    p.then(cb).finally(() => { 
        //Do something after the outer then has completed
        console.log("finally hit");
    });
    
    return p;
}

function doPromise() {
    getPromise(data => { console.log("then hit"); });
}

doPromise()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The successful execution of one promise determines the outcome of the $q.all promise

I am currently dealing with a situation where I have three nested promises that I need to refactor into a single $q.all call. The current structure of the code looks like this: ds.saveData(data).then(function (result1){ someOtherVar = result1.Id; ...

Issue with Angularjs: NG-repeat and filter not functioning correctly on array

After spending the last 3 hours searching on Google and Stack Overflow, I thought this would be easy, but I'm still stuck. I have a simple ng-repeat where I need to display everything from data2 that matches the unique ID in my data1's ref_id co ...

Just diving into JavaScript, what makes jQuery so powerful?

As a newcomer to javascript (although functional programming is no problem for me), I find myself questioning some of the design choices made by jQuery. Is it too late to make changes now, or are they simply too ingrained in the framework? For example, the ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

Is it feasible to amalgamate the states of several child components into a single parent component state in NextJS/React?

Issue I am faced with the challenge of handling multiple Child components that can pass their state to a Parent component. Now, I am looking to render several Parent components within a Grandparent component and merge the states of each Parent into a sing ...

Angular: extracting value from forkJoin nested within another observable's pipe

Here is the scenario that needs to be implemented: An API call is made which returns a response containing an array of objects. The objects are then mapped to another array of objects. For each item in this new array, another API call needs to be made. Th ...

What is the typical output value that fluctuates?

I only have one input to work with. My goal is to set the input value to "5", then display "3" in the "total" field and "4" in the "total2" field. Additionally, for every increment of +1 to the input value, I want the "total" and "total2" fields to also in ...

Navigating the terrain of multiple checkboxes in React and gathering all the checked boxes

I am currently developing a filter component that allows for the selection of multiple checkboxes. My goal is to toggle the state of the checkboxes, store the checked ones in an array, and remove any unchecked checkboxes from the array. Despite my attemp ...

How come I keep running into the "is not a function" issue when trying to use the generateRequest function with Polymer's iron-ajax

Oops, it seems like there was an error: Uncaught TypeError: this.$.ajax.generateRequest is not a function. The issue seems to be in assets-ajax.html at line 23. <dom-module id="assets-pull"> <style> </style> <template> <but ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

Choose the initial offspring from a shared category and assign a specific class identifier

I am trying to figure out how to apply the "active" class to the first tab-pane within each tab-content section in my HTML code. Here is an example of what I'm working with: <div class="tab-content"> <div class='tab-pane'>< ...

Identify the quantity of dynamically added <li> elements within the <ul> using jQuery

I'm facing an issue where I need to dynamically add a list of LI items to a UL using jQuery. However, when I try to alert the number of LI elements in this list, it only shows 0. I suspect that it's because the code is trying to count the origina ...

Retrieving parameters from the URL in Angular

I'm facing an issue with my app. I am currently using a factory to manage data for two controllers. When I click on a link that redirects me to another view with a specific URL, I want to reuse the last tag in the URL by slicing it like this: window. ...

Toggle display of divID using Javascript - Conceal when new heading is unveiled

At the moment, I have implemented a feature where clicking on a title reveals its corresponding information. If another title is clicked, it opens either above or below the previously opened title. And if a title is clicked again, it becomes hidden. But ...

Assistance with JavaScript Regular Expressions for formatting BBCode

A few weeks ago, I stumbled upon this regex expression: /([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig It's designe ...

Ways to disable an AJAX loading animation

In my current script, I am loading external content using the following code: <script type="text/javascript"> var http_request = false; function makePOSTRequest(url, parameters) { // Code for making POST request } function alertContents() { ...

After adding data to an empty array, index 0 becomes undefined for someEmptyArray

Currently, I am utilizing fs.readdir to generate an array of filenames within a specific directory. Additionally, I have implemented some regex functions to filter out undesirable filenames and/or filetypes. Upon executing the code provided below, I succe ...

An issue has occurred: it seems that the property cannot be accessed because `this.child` is undefined

Is there a way to call the function "initMap" that is defined in the child component "UpdatePinComponent", from the parent component named "ApiaryComponent"? Below is a snippet of the TypeScript code from the parent component: import { AfterViewInit, Compo ...

The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the color ...

The page refreshes automatically when the search icon is clicked, but the ajax method does not trigger the page reload

Whenever I click on the search-box <a>, the JavaScript is triggered but doesn't execute the ajax method filter_data_guide_specs(). Instead, the page automatically reloads and fails to read the JS code. HTML <div class="form-group"> < ...