(async () => { })(); what is this?

前端 未结 1 1572
我在风中等你
我在风中等你 2021-02-06 01:46
async function test() {
  (async () => {            
    var a = await this.test1();
    var b = await this.test2(a);
    var c = await this.test3(b);  
    this.doTh         


        
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 02:04

    Both return a promise but they return different promises.

    The first will return a promise that may resolve before this.test1()'s result resolves.

    The second returns a promise that only resolves after the final call to this.doThis(a,b,c);.

    This has been called the "fire and forget pattern":

    Often in application development you want a process to call another thread and continue the process flow, without waiting for a response from the called thread. This pattern is called the “fire and forget” pattern.

    You can see this in

    function logEventually(str) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(str);
          resolve(null);
        }, 0);
      });
    }
    
    async function a() {
      await logEventually('in a 1');
      await logEventually('in a 2');
      await logEventually('in a 3');
      return await logEventually('end of a');
    }
    
    async function b() {
      (async () => {
        await logEventually('in b 1');
        await logEventually('in b 2');
        await logEventually('in b 3');
      })();
      return await logEventually('end of b');
    }
    
    a();
    b();

    0 讨论(0)
提交回复
热议问题