【问题标题】:Async instead of then() for server.listen()server.listen() 的异步而不是 then()
【发布时间】:2019-04-17 01:23:36
【问题描述】:

这是启动 apollo 服务器的方式:

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

我想使用 async/await 合成器。所以我试着做 - 这是错误的:

server.listen(port, async ({ url }) => {
  await anyFunction()
  console.log(`Server ready at ${url}`)
})

【问题讨论】:

    标签: javascript node.js asynchronous apollo


    【解决方案1】:

    async-await 的行为与.then() 链类似,await 等待承诺得到解决或拒绝,然后继续处理,就像.then() 继续承诺解决和.catch() 承诺拒绝。

    await 返回的结果与.then() 获得承诺解决的结果相同,即:

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

    同样,try-catch 中的 catch(err).then()-.catch() 中的 .catch( function(err) {}) 得到相同的错误。

    详细了解async-await herehere

    要将您的 .then() 转换为 async-await,只需执行以下操作:

    (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-await 作为一个函数:

    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】:

    你必须await承诺返回,不要退回到回调风格:

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

    【讨论】:

      【解决方案3】:

      您必须将函数作为整个代码块包含在 async。然后,就像在server.listen 上调用.then 一样,您可以改为await server.listen(...

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

      确保也捕获错误 - 无论是在 foo 的使用者中:

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

      或者在foo内的catch块中:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        • 1970-01-01
        • 2020-01-09
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        相关资源
        最近更新 更多