zoukankan      html  css  js  c++  java
  • 用同步的写法来执行异步操作, 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发送请求数据

     

  • 相关阅读:
    单例模式
    反射常见方法
    字符流,字节流总结
    泛型限定
    随机数判断最值
    字符流与字节流练习
    文件常见操作属性
    文件过滤器
    字符流读取文件
    目前最流行的IT编程语言
  • 原文地址:https://www.cnblogs.com/fsg6/p/14408601.html
Copyright © 2011-2022 走看看