JS报错问题解决 {(intermediate value)(intermediate value)} is not a function

跟着教程学习async的使用,遇到问题老师竟然跳过了跳过了跳过了!强迫症简直不能忍!

以下就是报错代码,简直就是大家来找茬,

    function fn() {
    	return new Promise( (resolve)=>{
    		setTimeout( ()=>{
    			console.log("hi");
    			resolve("0");
    		},1000);
    	});
    }

    var obj = {
        say: async ()=>{
            const res = await fn();
            console.log(`res ${res}`);
        },
        run: async ()=>{
            await fn();
            console.log(`run`);
        }
    }

    (async function(){
        await obj.say();

        await obj.run();
    })()

最开始报错我以为是匿名函数的原因,将其都修改为了function(),可还是不对,我又将其赋值给f1,但此次并没有报错,结果也成功打印。

    // (async function(){
    //     await obj.say();

    //     await obj.run();
    // })()

    var f1 = async ()=>{
    	await o1.say();

    	await o1.run();
    }

    f1();

发现不是匿名函数的问题,我仔细检查了代码,增加了分号,就通过了编译。

    function fn() {
    	return new Promise( (resolve)=>{
    		setTimeout( ()=>{
    			console.log("hi");
    			resolve("0");
    		},1000);
    	});
    }

    var obj = {
        say: async ()=>{
            const res = await fn();
            console.log(`res ${res}`);
        },
        run: async ()=>{
            await fn();
            console.log(`run`);
        }
    }; // 分号在此

    (async function(){
        await obj.say();

        await obj.run();
    })()

 我们都知道JS是可以不写分号由其自动添加的,但JS并不是一行末尾添加的,它的机制很有趣,会进行解析,能够正常被解析的时候才在末尾增加分号,而解析不了的时候就会合并下一条语句。

所以我的代码在它的眼中应该是这样的,这不报错就出鬼了。

    function fn() {
    	return new Promise( (resolve)=>{
    		setTimeout( ()=>{
    			console.log("hi");
    			resolve("0");
    		},1000);
    	});
    }

    var obj = {
        say: async ()=>{
            const res = await fn();
            console.log(`res ${res}`);
        },
        run: async ()=>{
            await fn();
            console.log(`run`);
        }
    }(async function(){
        await obj.say();

        await obj.run();
    })();

最后,希望大家都养成语句结尾手动增加分号的好习惯,远离低级错误。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值