简体   繁体   中英

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 -
在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM