You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Protractor自动化脚本中获知回调REST调用的响应?

理解你的HTTP GET调用响应时机与确认方式

Hey there! Let's break down how your code handles response timing and how you can confirm when the response has fully arrived:

1. 响应开始的触发时机

When the HTTP server sends back the first byte of its response, the callback you passed to http.get (that function(response) { ... } block) will run. This is your first signal that the server has started sending a response, and the response object gives you access to all response-related details.

2. 确认响应完全到达的核心标志

Your code already uses the two critical events to track full response completion:

  • The data event: Fires every time a chunk of response data comes in. You're already concatenating these chunks into bodyString to build the full response body.
  • The end event: This is the definitive signal that the entire response has been received. All response data has been sent, and there's nothing left to process. You're already using this event to resolve your Promise with the complete status code and body—so when your then callback (function(result) { ... }) runs, you can be 100% sure the response is fully here.

3. Handling error scenarios

You also added an error event listener, which triggers if there's a problem like a network failure or invalid URL. When this fires, your Promise rejects, letting you know the request failed before a full response could be received.

A small optimization tip

If you're using a modern Node.js version, you can simplify your code with util.promisify to avoid manual defer setup, but your existing logic is totally valid. Here's a cleaned-up version:

const http = require('http');
const { promisify } = require('util');

// Wrap http.get in a Promise for cleaner syntax
const httpGet = promisify((url, callback) => {
  http.get(url, (response) => {
    let bodyString = '';
    response.setEncoding('utf8');
    response.on('data', (chunk) => bodyString += chunk);
    response.on('end', () => callback(null, { statusCode: response.statusCode, bodyString }));
  }).on('error', (e) => callback(e));
});

// Usage
httpGet("http://testurl")
  .then(result => {
    console.log('Response fully received!', result);
  })
  .catch(err => {
    console.error('Request failed:', err);
  });

Quick recap:

  • Response starts: When the http.get callback runs
  • Response fully received: When the end event fires, or when your Promise's then callback executes
  • Request failed: When the error event fires, or when your Promise's catch callback executes

内容的提问来源于stack exchange,提问作者shaaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:10:35