跟着教程学习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();
})();
最后,希望大家都养成语句结尾手动增加分号的好习惯,远离低级错误。