2016-12-23 1 views
0

긴 풀링 요청을 만들고 싶습니다. 그래서 나는 약간의 지연 후에 요청을하고 응답을 보내고 싶다. 가능한가? Koa 2 라우터 긴 폴링 요청을하는 방법

내가 비동기/await를 SYNAX 사용하려고 해요하지만 나를 위해 작동하지 않는 것 어떤 도움

많은 감사 (I 클라이언트에 오류 404을 가지고). 여기

내 서버입니다

import 'babel-polyfill'; 
import Koa from 'koa'; 
import Router from "koa-router"; 

import fs from "fs"; 


const router = new Router(); 

const convert = require('koa-convert') 
const serve = require("koa-static"); 

const app = new Koa(); 


router 
    .get('/*', async function (ctx, next) { 



      ctx.response.type = 'text/html; charset=utf-8'; 

      /* await (() => { 
       setTimeout(() => {ctx.body = fs.readFileSync(__dirname + "/public/index.html")}, 1000) 
      })(); */ 

      //ctx.body = fs.readFileSync(__dirname + "/public/index.html"); 


    }) 

app.use(convert(serve(`${__dirname}/public`))) 
app.use(router.routes()).use(router.allowedMethods()); 

app.listen (3000);

답변

3

일반적으로 예. 이것은 가능하다.

코드의 문제점은 await이 약속을 기반으로한다는 것입니다. 그래서 당신의 타임 아웃 기능은 약속으로 캡슐화되어야합니다. 이 같은 것이 작동 할 수 있습니다.

... 
function delayed(ctx, ms) { 
    return new Promise((resolve, reject) => { 
     setTimeout(function() { 
      ctx.body = fs.readFileSync(__dirname + "/public/index.html") 
      resolve(); 
     }, ms); 
    }) 
} 

router.get('/*', async function (ctx, next) { 
    ctx.response.type = 'text/html; charset=utf-8'; 
    await delayed(ctx, 1000); 
}) 
... 
+0

Sebastian에 감사드립니다. – Velidan