perform unique actions by file after a promise resolves

In a Vue project, there is a chunk of code that’s repeated in several files and I’m trying to refactor it into a helper function so it can be shared by the files that need it. The purpose of said code block is to display toasts in the UI based on the outcome of an API promise. The catch is that after the toasts are displayed different files must perform actions specific to that file. For instance, one file must refresh data while another file must close a modal form. This means waiting for the common code that displays toasts to finish before calling subsequent commands. That is where I’m stuck.

This simplified code replicates the issue in the larger project:

// simulate an API promise
const aPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise resolved at ' + new Date().toLocaleString());
  }, 2000);

// get simulated API promise
const response = aPromise;

// --- this works ---
const generateResponseFeedback = response
    .then((msg) => {console.log(msg)})
    .then(() => {console.log('second message ' + new Date().toLocaleString())});

const response2 = generateResponseFeedback.then(() => { console.log('last message abc ' + new Date().toLocaleString())});

// --- this does not work ---
const sharedGenerateResponseFeedback = (response) => {
    response.then((msg) => {console.log(msg)})
    .then(() => {console.log('second message ' + new Date().toLocaleString())});

sharedGenerateResponseFeedback(response).then(() => { console.log('last message xyz ' + new Date().toLocaleString())});

The console displays the following –
enter image description here

I don’t understand why it’s saying sharedGenerateResponseFeedback(...) is undefined. Why doesn’t it recognize that function name?


You need to return the promise in sharedGenerateResponseFeedback.

const sharedGenerateResponseFeedback = (response) => {
    return response.then((msg) => {console.log(msg)})
    .then(() => {console.log('second message ' + new Date().toLocaleString())});

Leave a Reply

Your email address will not be published. Required fields are marked *