最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Async instead of then() for server.listen() - Stack Overflow

programmeradmin2浏览0评论

This is how a apollo server is started:

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

I would like to use the async/await synthax. So I tried to do - which is wrong:

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

This is how a apollo server is started:

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

I would like to use the async/await synthax. So I tried to do - which is wrong:

server.listen(port, async ({ url }) => {
  await anyFunction()
  console.log(`Server ready at ${url}`)
})
Share Improve this question asked Nov 14, 2018 at 6:06 user3142695user3142695 17.4k55 gold badges199 silver badges375 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

async-await behaves a similar way as of .then() chain, await waits for promise to get resolved or rejected and then continue process just like .then() continue on promise resolve and .catch() on promise reject.

await returns same result that .then() get on promise resolve, i.e:

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

similarly catch(err) in try-catch gets same error as by .catch( function(err) {}) in .then()-.catch().

Learn more about async-await here and here.

To convert your .then() to async-await just do this:

(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 as a function:

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

startServer();    // Not an IIFE

You would have to make the function the whole code block is contained in async. Then, just as how .then is being called on server.listen, you would await server.listen(... instead:

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

Make sure to catch errors, too - either in the consumer of foo:

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

or in a catch block inside foo:

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

You have to await the promise returned, don't fall back to callback style:

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

评论列表(0)

  1. 暂无评论