如何使用Highland的wrapCallback处理n元函数?以jsonist.get为例
Great question! Let's clear up the confusion here—Highland's wrapCallback absolutely supports functions with multiple leading arguments (like jsonist.get's uri and options), your issue is just about how you're consuming the resulting stream.
What Was Wrong With Your Original Code
When you do req(uri, options).apply(H.log), you're creating a valid Highland Stream, but you're not properly triggering the stream to execute or extract the data. apply(H.log) is not the right method here—you need to use stream consumption methods to actually get the response data instead of just seeing the stream object itself.
Correct Implementation
Here's how to properly wrap and use jsonist.get with Highland:
const H = require('highland'); const jsonist = require('jsonist'); // Wrap jsonist.get: wrapCallback automatically handles the first two parameters // and passes them to jsonist.get before the generated callback const getJson = H.wrapCallback(jsonist.get); // Example usage: pass uri and options, then consume the stream const uri = 'https://api.example.com/your-endpoint'; const options = { headers: { 'Authorization': 'Bearer your-token', 'Accept': 'application/json' } }; // Option 1: Use .pipe() with H.log() to print the data getJson(uri, options) .on('error', err => console.error('Request failed:', err)) // Handle errors .pipe(H.log()); // Option 2: Use .each() for custom data handling getJson(uri, options) .on('error', err => console.error('Request failed:', err)) .each(data => { console.log('Received response:', data); // Do something with the data here });
Key Explanations
wrapCallbackWorks With Multiple Args: Highland'swrapCallbacktakes a function where the last argument is a standard(err, result)callback. All leading arguments (likeuriandoptions) are preserved when you call the wrapped function—you just pass them in order, and Highland passes them tojsonist.getbefore attaching its own callback.- Stream Consumption: To get the actual data, you need to consume the stream. Methods like
.pipe(),.each(), or.toArray()trigger the stream to execute the async function and emit the result. - Error Handling: Don't forget to listen for the
errorevent—any errors fromjsonist.get(like network issues, HTTP errors) will be emitted here instead of crashing your app.
Why Your Original Code Showed the Stream Instead of Data
req(uri, options) returns a Highland Stream object immediately (before the async request completes). When you called .apply(H.log), you weren't actually consuming the stream—you were just calling a method on the stream object, which doesn't trigger the request or extract the data. Using proper consumption methods like .pipe() or .each() tells Highland to run the async function and emit the result once it's ready.
内容的提问来源于stack exchange,提问作者sqldoug

