代码之家  ›  专栏  ›  技术社区  ›  user3142695

server.listen()的异步而不是then()

  •  0
  • user3142695  · 技术社区  · 7 年前

    以下是阿波罗服务器的启动方式:

    server.listen(port).then(({ url }) => {
      console.log(`Server ready at ${url}`)
    })
    

    server.listen(port, async ({ url }) => {
      await anyFunction()
      console.log(`Server ready at ${url}`)
    })
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   NAVIN    7 年前

    async-await 行为与……相似 .then() await .然后() 继续承诺和决心 .catch() 拒绝承诺。

    foo().then( function(result){}); // got result here
    result = await foo(); // will get same result here too as in above function.
    

    同样地 catch(err) 在里面 try-catch .catch( function(err) {}) 在里面 .then()-.catch() .

    async-await here here .

    (async function () {
        try {
            const { url } = await server.listen(port);
            console.log(`Server ready at ${url}`);
        } catch(e) {
            // handle errors
        }
    })();      // This is [IIFE][3]. In this case it's better to have IIFE then regular function, as functions needed to be called.
    

    异步等待作为一个函数:

    async function startServer() {
        try {
            const { url } = await server.listen(port);
            console.log(`Server ready at ${url}`);
        } catch(e) {
            // handle errors
        }
    }
    
    startServer();    // Not an IIFE
    
        2
  •  2
  •   CertainPerformance    7 年前

    包含在 async . 那么,怎么办呢 .then server.listen ,你会的 await server.listen(... 相反:

    async function foo() {
      // ...
      const { url } = await server.listen(port);
      console.log(`Server ready at ${url}`);
    }
    

    foo :

    foo()
      .catch((err) => {
        // handle errors
      });
    

    catch :

    async function foo() {
      try {
        const { url } = await server.listen(port);
        console.log(`Server ready at ${url}`);
      } catch(e) {
        // handle errors
      }
    }
    
        3
  •  2
  •   Jonas Wilms    7 年前

    你必须 await 返回 ,不要退回回回调样式:

     (async function () {
        const url = await server.listen(port);
        console.log(`Server listening at "${url}"`);
     })();