Why does Promise.then() only work with arrow functions?

I am trying to handle a Promise in Javascript, and as a beginner I find the shorthand arrow functions a bit hard to read. So for now I like to expand it to be function(){ } rather than ()=>.

When handling a Promise, the following does not work:

defineAsyncComponent(()=>{
      return import('@ckeditor/ckeditor5-vue/dist/ckeditor.js').then( function(module) {
        module.component
      }).catch(function(error) {
        console.log(error)
      })
    })

However if I change it to use arror functions then it does work:

defineAsyncComponent(()=>{
      return import('@ckeditor/ckeditor5-vue/dist/ckeditor.js').then((module) => module.component).catch((error) => console.log(error))
    })

What on earth is the difference between to the two to cause the first one not to work entirely?

Answer

I believe the reason it does not work is because you do not return anything from that promise.

Try the following:

defineAsyncComponent(() => {
      import('@ckeditor/ckeditor5-vue/dist/ckeditor.js').then(function(module) {
        return module.component;
      }).catch(function(error) {
        console.log(error);
      })
    });

Arrow functions without {} implicitly return.

Leave a Reply

Your email address will not be published. Required fields are marked *