【问题标题】:What's the arrow-function doing in this code?这段代码中的箭头函数是做什么的?
【发布时间】:2016-09-26 00:33:40
【问题描述】:

代码来自 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() 函数接受三个参数 - 如果没有 options 对象(用户省略了它)并且它已被替换为函数:用户试图实现一个回调函数——将回调更改为optscb = opts

其次,如果引用的文件是文本文件 &&http 开头 - 它显然是远程托管的,我们需要使用 Wreck 获取它。

所有这些我都明白,但我们为什么要使用(send) => 箭头函数?为什么我们使用return function add...send('add', null, opts, res, cb)return send('add', null, opts, res, cb) 是干什么用的?回调(cb)是如何实现的?帮助我了解这里发生了什么

【问题讨论】:

  • 这只是一个工厂函数,生产其他函数并在内部调用它们。模块不再需要,但有些人仍然坚持这种模式。
  • @ssube:它被用于进行依赖注入(send 是被注入的依赖)。模块如何使它变得不必要? (真正的问题。)

标签: javascript callback arrow-functions ipfs


【解决方案1】:

整个被导出的是一个函数,它期望send作为一个参数;这允许调用代码通过传入要使用的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的测试版本进行测试,并通过注入send的真实版本来使用它;和/或send 的各种“真实”版本可用于不同的环境、传输机制等。

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多