【问题标题】:TypeError: Cannot read property 'then' of undefined --got this error while using thenTypeError: Cannot read property 'then' of undefined -- 使用 then 时出现此错误
【发布时间】:2020-05-11 18:49:34
【问题描述】:

我尝试了以下代码,因为节点是异步类型,以便按顺序运行我的代码,我添加了 then 函数,但我收到错误 TypeError: Cannot read property 'then' of undefined。我使用了下面的代码

    va

r arr =[]
    exceltojson({
       input: 'test.xlsx',
       output: 'test.json',// Don't need output
       sheet: 'test'
     },
     function(err, result) {
       if (err) {
         console.error(err);
       } 
    }
    )
    .then() {
      // var msg ='done';
       updateFlag();
       })

    function updateFlag(){
       console.log('end')
    }
    I expect the output like 

conversion done

    end

【问题讨论】:

  • 你的函数应该返回 Promise for then 工作当前它返回 undefined。请同时发布 exceltojson
  • 你的函数应该返回promise,然后才能工作——你能分享一些参考吗
  • mongoose 本身就支持 Promise,你的库可能支持也可能不支持库
  • 不使用promise return,有没有可能使这段代码连续?

标签: javascript node.js json


【解决方案1】:

您的函数 exceltojson 不是返回承诺,这就是问题所在。我已将您的功能转换为承诺。请尝试下面给出的代码。

function promiseExcelToJson() {
return new Promise((res, rej) => {
    exceltojson({
        input: 'test.xlsx',
        output: 'test.json',
        sheet: 'test'
      },
      function(err, result) {
         if(!err) { 
         console.log('conversion done') 
         res(result) 
        } else 
          rej(result)
      }

    )
})
}

var arr =[]
promiseExcelToJson().then(()=> {
    updateFlag();
})
function updateFlag(){
console.log('end')
}

希望这会有所帮助!告诉我!

【讨论】:

  • 为什么要在 promise 中包装一个带有回调的函数? .这根本没有意义
  • Promises 用于以同步方式运行回调,这就是我将其包装在 Promise 中的原因。他正在使用一个函数,他想在执行回调后执行某些操作。
  • 那你为什么要在里面传递一个回调函数??请解释
  • 以及为什么异步函数,异步函数固有地返回承诺包装值,因此您不需要在其中显式返回承诺
  • 看,excelTOJson是一个函数,在得到结果或错误后最终会运行回调。现在,开发人员的动机是在回调调用完成后做一些事情。开发人员也可以在回调中做任何他想做的事情,但在一个函数中做所有事情并不是一个好主意。所以,我做出了一个承诺,将解决回调,在解决回调之后,我们可以使用 .then 来执行我们的动机。
猜你喜欢
  • 1970-01-01
  • 2018-07-16
  • 2018-11-01
  • 2016-10-28
  • 2020-03-03
  • 2016-11-02
  • 2020-09-20
  • 2022-01-11
  • 2020-11-07
相关资源
最近更新 更多