繁体   English   中英

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

[英]perform unique actions by file after a promise resolves

在 Vue 项目中,有一段代码在多个文件中重复,我试图将其重构为帮助程序 function,以便可以由需要它的文件共享。 所述代码块的目的是根据 API promise 的结果在 UI 中显示祝酒词。 问题是,在显示 toast 之后,不同的文件必须执行特定于该文件的操作。 例如,一个文件必须刷新数据,而另一个文件必须关闭模式表单。 这意味着在调用后续命令之前等待显示 toast 的通用代码完成。 那就是我卡住的地方。

这个简化的代码在更大的项目中复制了这个问题:

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

控制台显示以下内容 -
在此处输入图像描述

我不明白为什么它说sharedGenerateResponseFeedback(...)未定义。 为什么它不识别 function 名称?

您需要在 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