首页 > 解决方案 > 如何使用导入的函数作为承诺。Object(...)(...).then 不是函数

问题描述

我有以下问题。我在一个单独的文件中创建了这个函数

    import Cookies from 'js-cookie';
import jwtDecode from 'jwt-decode';

export default function checkLifeExpectancySet(){
    var decoded = [];
    decoded.permited = [];
    var accesstoken = Cookies.get('accesstoken');


    if((accesstoken)){
     var decoded  = jwtDecode(accesstoken)
    }
    //if it includes the life_expectancy it means it hasnt been set
    if(decoded.permited.includes("life_expectancy")){
        return false;
    }
}

然后我这样称呼它

checkLifeExpectancySet().then((result) =>{
          if(result == true){
            //the lifeExpectancy is yet to set
            this.props.lifeExpectancySet(false)
          }else{
            //the lifeExpectancy was already set
            this.props.lifeExpectancySet(true)
          }
        })

但它返回

TypeError: Object(...)(...).then 不是函数

我认为这是一个问题,因为它不是承诺或其他东西,我将如何将其转换为承诺或等待结果?我现在迷路了

标签: javascriptreactjs

解决方案


jwtDecode 没有返回承诺,因此,如果您想返回承诺,请执行此操作。

export default function checkLifeExpectancySet(){

    return new Promise((resolve, reject) => {

       let decoded;
       const accesstoken = Cookies.get('accesstoken');

       if(accesstoken){
          decoded  = jwtDecode(accesstoken)
       }

       // your other logic.

       // if you want to throw error, uncomment below line.
       // return reject(new Error('some reason'));

       return resolve(decoded);

    });

}

推荐阅读