如何在Protractor自动化脚本中获知回调REST调用的响应?
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
dataevent: Fires every time a chunk of response data comes in. You're already concatenating these chunks intobodyStringto build the full response body. - The
endevent: 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 yourthencallback (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.getcallback runs - Response fully received: When the
endevent fires, or when your Promise'sthencallback executes - Request failed: When the
errorevent fires, or when your Promise'scatchcallback executes
内容的提问来源于stack exchange,提问作者shaaa

