[英]Why does Promise.then() only work with arrow functions?
我正在嘗試在 Javascript 中處理Promise
,作為初學者,我發現速記arrow functions
有點難以閱讀。 所以現在我喜歡將它擴展為function(){ }
而不是()=>
。
處理 Promise 時,以下操作不起作用:
defineAsyncComponent(()=>{
return import('@ckeditor/ckeditor5-vue/dist/ckeditor.js').then( function(module) {
module.component
}).catch(function(error) {
console.log(error)
})
})
但是,如果我將其更改為使用arror functions
,那么它確實可以工作:
defineAsyncComponent(()=>{
return import('@ckeditor/ckeditor5-vue/dist/ckeditor.js').then((module) => module.component).catch((error) => console.log(error))
})
兩者之間到底有什么區別導致第一個不能完全工作?
我相信它不起作用的原因是因為你沒有從那個 promise 返回任何東西。
嘗試以下操作:
defineAsyncComponent(() => {
import('@ckeditor/ckeditor5-vue/dist/ckeditor.js').then(function(module) {
return module.component;
}).catch(function(error) {
console.log(error);
})
});
沒有{}
的箭頭函數隱式return
。
我認為在這種情況下它與“ this ”上下文有關(常規函數和箭頭函數都有,但使用方式不同)。
當使用 promise 的“then”方法時,您希望將 promise 的響應(無論是解決還是拒絕)傳遞給它。 現在,當“then”被調用時,它會問“誰在給我打電話?”,這就是你的答案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.