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

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

Please input new items by clicking a button

I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

What is the best way to make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

Inaccurate recommendations for type safety in function overloading

The TypeScript compiler is not providing accurate suggestions for the config parameter when calling the fooBar function with the 'view_product' type. Although it correctly identifies errors when an incorrect key is provided, it does not enforce t ...

Utilizing .html() to convert JSON data into HTML content

I have thoroughly commented the code below in my attempt to retrieve JSON data and pass it to the 'results' div in my HTML view. However, this process seems to return nothing, making it challenging to debug since no output can be displayed on the ...

The art of selecting elements and attaching event listeners in a React environment

Currently, I am working on my portfolio website using Gatsby. The layout includes a sidebar on the left with navigational links (Home, About, Work, etc.), and the main content is displayed as one long strip of sections on the right. When a user clicks on a ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

When attempting to access endpoints from other computers, the connection to Express.js is being refused

I have set up an Express server and React for the frontend. The express server is running on port 5000 and React on port 3000. Additionally, I am using JWT tokens for authentication. When I login to the app from the computer it is running on, everything w ...

Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'}, {id: ...

The .push method in Javascript is failing to execute

I'm facing a challenge with this particular code snippet. Essentially, I am attempting to loop through an array of Word objects and categorize them based on word type using a switch statement. This process is triggered by jQuery listening for a button ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

Manipulating the DOM to show various elements upon clicking on text

Currently, I am engaged in a small project that involves experimenting with DOM manipulation. The project revolves around creating a Todo list where users can generate various categories (such as work, gym, finances, etc.) and then add corresponding subtas ...

What are the Typescript object types where the keys are functions that take a single generic argument consistently?

Explaining this concept in English is quite challenging, but here's what I'm aiming for: const operations = { store: (input: T): T => { return input; }, discard: (input: T): void => { console.log(input); } } In both fun ...

Having two identical select2 forms on the same page

Integrating two select2 multi-value select boxes into my Rails application is proving to be a challenge. While the top form functions correctly, the bottom one refuses to work as expected. Despite my attempts at changing IDs and adding new JavaScript cod ...

Can you explain the concept of the "one true source"?

After reviewing this particular article, I came across a significant statement in the "Controlled Components" section: The integration of both can be achieved by ensuring that the React state is considered as the “single source of truth”. Can you ...

What is the best way to incorporate Javascript into jQuery tabs?

On my website, I have implemented a Jquery and CSS tab system similar to the one found here. Each tab contains a Facebook feed box, a Twitter widget, and a ranking widget for my blog. However, when these widgets are placed within the tab content area, they ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...