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

时间:2018-11-14 06:06:46

标签: javascript node.js asynchronous apollo

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

    function () {
        debugger;

        $("#Mastergrid").kendoGrid({
            height:550,
            sortable: false,
            reorderable: true,
            scrollable: true,
            selectable: "row",
            resizable: true,
            editable: false,
            autoFitColumn: true,
            Autosize : true ,
            pageable: {
                pageSizes: [10, 15, 20, 25],
                pageSize: 10
            },             
            change: function (e) {
                debugger;
                MasterObject._selectedRow = this.select().closest("tr").children("td");
            }
        });
        function onDataBound() {
            var grid = $("#Mastergrid").data("kendoGrid");
            for (var i = 0; i < grid.columns.length; i++) {
                grid.autoFitColumn(i);
            }

        }
    },

我想使用异步/等待合成器。所以我试着做-这是错误的:

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

3 个答案:

答案 0 :(得分:2)

您必须使该函数的整个代码块均包含在{em> 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内的foo块中:

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

答案 1 :(得分:2)

您必须await兑现承诺已返回,不要退回回调样式:

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

答案 2 :(得分:2)

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.

catch(err)中的try-catch类似,错误与.catch( function(err) {})中的.then()-.catch()同样。

详细了解async-await herehere

要将您的.then()转换为异步等待,只需执行以下操作:

(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