简体   繁体   English

异步箭头功能和异步IIFE有什么区别?

[英]What is the difference between async arrow function and async IIFE?

Can someone please help me understand the difference (if there is a difference) in how these blocks are executed: 有人可以帮我理解这些块的执行方式之间的区别(如果有区别):

;(async function(){
  await alert('Hello world!');
})();

and

let myFunction = async () => {
  await alert('Hello world!');
};

Apart from the fact that the IIFE is immediately self-invoked, is there any difference in how these blocks are executed? 除了IIFE是立即自动调用的事实之外,这些块的执行方式是否有任何区别?

Your example is not a good example because you are not performing an asynchronous action within your async function. 您的示例不是一个好示例,因为您没有在异步函数中执行异步操作。 alert is synchronous, as in javascript execution will halt until it returns. 警报是同步的,因为在javascript中执行将暂停直到返回。 This makes the await keyword usage here pointless. 这使得await关键字在这里毫无意义。

The only difference I see is that you are not assigning the resulting promise to a variable in the iife, which means if you were performing an async action you would not be able to execute code when it is finished. 我看到的唯一区别是,您没有将生成的Promise分配给iife中的变量,这意味着,如果您正在执行异步操作,则在完成时您将无法执行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM