简体   繁体   中英

Chaining functions

I am currently trying to use the got module https://www.npmjs.com/package/got but I am a bit confused on the format/order of functions. It's evident that you can chain the listeners and functions as such

 got.stream(link)
 .on('response', resp => {
   if (resp.statusCode != 200) this.emit('error', '!200')
 })
 .on('error', err => {
   console.log(err)
 })
 .pipe(somewhere)

The request module also does this. But how do you avoid .pipe if you want it to happen only on the condition resp.statusCode != 200 ? Seeing that it's used in a lot of request modules, it must be a very basic thing to understand but I can't quite grasp it.

You don't need to chain it if you don't want to, and in this situation, you don't want to. Here's a simplified example of you'd do it without chaining:

const gotStream = got.stream(link);
gotStream.on('response', resp => {
    if(resp.statusCode == 200) {
        gotStream.pipe(somewhere);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM