异步自调用函数的 Javascript 语法

4 javascript asynchronous promise arrow-functions

在 JS 中可以编写一个带有 async 的自调用箭头函数,如下所示:

(async () => {
    const promis = fetch(uri);
    console.log(await promis);
})();
Run Code Online (Sandbox Code Playgroud)

一个没有参数的自调用函数我也可以这样写:

{
   // do something
}
Run Code Online (Sandbox Code Playgroud)

我问自己,是否有一种语法可以将两者结合起来并执行类似的操作,或者第一个示例已经是最短的形式?

// this is not working
async {
   const promis = fetch(uri);
   console.log(await promis);
}
Run Code Online (Sandbox Code Playgroud)

马长昆*_*man 8

有两种方法,我们可以短一点:)

  1. 简单的方法
!async function () {
    console.log("e",'yibu');
}();
Run Code Online (Sandbox Code Playgroud)

或者像你的一样

(async  () => {
    console.log("e",'yibu');
})();

//maybe this is better then above
;(async function () {
    console.log("e",'yibu');
}());

//this is allmost same
;[ async function () {
    console.log("e",'yibu');
}()];
Run Code Online (Sandbox Code Playgroud)
  1. 使用[那么]这不是绝对的“匿名”
var x=async  () => 100;

x().then(
    e=>console.log({e})
);
Run Code Online (Sandbox Code Playgroud)