简体   繁体   English

promise 解析后按文件执行唯一操作

[英]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.在 Vue 项目中,有一段代码在多个文件中重复,我试图将其重构为帮助程序 function,以便可以由需要它的文件共享。 The purpose of said code block is to display toasts in the UI based on the outcome of an API promise.所述代码块的目的是根据 API promise 的结果在 UI 中显示祝酒词。 The catch is that after the toasts are displayed different files must perform actions specific to that file.问题是,在显示 toast 之后,不同的文件必须执行特定于该文件的操作。 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.这意味着在调用后续命令之前等待显示 toast 的通用代码完成。 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.我不明白为什么它说sharedGenerateResponseFeedback(...)未定义。 Why doesn't it recognize that function name?为什么它不识别 function 名称?

You need to return the promise in sharedGenerateResponseFeedback .您需要在 sharedGenerateResponseFeedback 中返回sharedGenerateResponseFeedback

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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