轮询

在后续请求中产生不同的响应。

你可以在 JavaScript 中使用 生成器函数(包括异步生成器)在对端点的每个后续请求上产生不同的响应。这对于描述 HTTP 轮询特别方便。

¥You can use generator functions (including async generators) in JavaScript to yield different responses on each subsequent request to an endpoint. This is particularly handy to describe HTTP polling.

import { http, HttpResponse, delay } from 'msw'
 
export const handlers = [
  http.get('/weather/:city', async function* () {
    let degree = 25
 
    // Add random server-side latency to emulate
    // a real-world server.
    await delay()
 
    while (degree < 27) {
      degree++
      yield HttpResponse.json({ degree: degree })
    }
 
    degree++
    return HttpResponse.json({ degree: degree })
  }),
]

上面的示例将以递增的温度度数进行响应,直到达到 28 度。

¥The example above will respond with incrementing temperature degree until it reaches 28 degrees.

GET /weather/london // { "degree": 26 }
GET /weather/london // { "degree": 27 }
GET /weather/london // { "degree": 28 }
// All subsequent requests will respond
// with the latest returned response.
GET /weather/london // { "degree": 28 }