用同步的写法来执行异步操作, async, awiat

const router = require("koa-router")();

router.get("/", async (ctx, next) => {
  global.console.log("index8");
  await ctx.render("index", {
    title: "Hello Koa 2!",
  });
});

router.get("/string", async (ctx, next) => {
  ctx.body = "koa2 string";
});

router.get("/json", async (ctx, next) => {
  ctx.body = {
    title: "koa2 json",
  };
});

router.get("/test", async (ctx) => {
  global.console.log('start', new Date().getTime());
  const a = await new Promise((resolve, reject) => {
    setTimeout(() => {
      global.console.log('async a' + new Date().getTime());
      resolve("promise");
    }, 1000);
  });

  const b = await 12
  const c = await Promise.resolve('c')

  ctx.body= {
    a,
    b,
    c
  };
});

module.exports = router;

用同步的写法来执行也不操作, async, awiat

只有a,b,c全部都返回了数据,才会ctx.body发送请求数据

 

原文地址:https://www.cnblogs.com/fsg6/p/14408601.html