javascript – 这个代码中的箭头函数是做什么的?

代码来自IPFS(行星际文件系统)HTTP API JS实现:
https://github.com/ipfs/js-ipfs-api/blob/master/src/api/add.js

'use strict'

const Wreck = require('wreck')

module.exports = (send) => {
    return function add(files, opts, cb) {
        if (typeof(opts) === 'function' && cb === undefined) {
            cb = opts
            opts = {}
        }
        if (typeof files === 'string' && files.startsWith('http')) {
            return Wreck.request('GET', files, null, (err, res) => {
                if (err) return cb(err)

                send('add', null, opts, res, cb)
            })
        }

        return send('add', null, opts, files, cb)
    }
}

所描述的功能是add()函数,用于将数据推送到IPFS.

我将从解释我理解的内容开始:add()函数接受三个参数 – 如果没有选项对象(用户省略它)并且它已被函数替换:用户正在尝试实现回调函数 – 将回调更改为opts; cb =选择.

其次,如果引用的文件是文本文件&&从http开始 – 它显然是远程托管的,我们需要使用Wreck来获取它.

所有这些我理解,但为什么我们使用(发送)=>箭头功能?为什么我们使用return function add …?什么是send(‘add’,null,opts,res,cb)和return send(‘add’,null,opts,res,cb)用于?如何实现回调(cb)?帮助我了解这里发生了什么

最佳答案 导出的整个东西是一个函数,它将发送作为参数;这让调用代码通过传入send函数来进行依赖注入.它希望使用这样的东西:

let addBuilder = require("add");
let add = addBuilder(senderFunction);
// This function ----^
// is `send` in the `add.js` file.
// It does the actual work of sending the command

// Then being used:
add(someFiles, someOptions, () => {
    // This is the add callback, which is `cb` in the `add.js` file
});

(通常,上面的前两个语句是作为单个语句编写的,例如let add = require(“add”)(senderFunction);)

基本上,整个事情是一个使用给定发送函数的大型构建器,通过调用构建器将其注入其中.这样,它可以通过注入send的测试版本来测试,并通过注入真实版本的send来用于实际;和/或各种“真实”发送版本可用于不同的环境,传输机制等.

点赞