[英]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.