如何确定回调函数的参数列表

How to determine parameter list of callback functions

本文关键字:参数 列表 函数 何确定 回调      更新时间:2023-09-26

在D3.js中,有时我会传递一个回调函数作为参数,例如下面的In delay((:

d3.select('body').selectAll('div')
  .data(distances)
  .enter()
  .append('div')
  .html('.')
  .style('width', '10px')
  .style('opacity', 0)
  .transition()
    .delay(function(d, i) { return i * 1000 })

问题:我们怎么知道回调函数应该有两个参数:d 和 i。它在什么文档中指定"d"应该对应于基准,"i"对应于索引?

我的问题不仅限于 D3.js而是一般的 js 约定。 例如,在Angular.js中,我发现了类似的东西。 例如,在下面传递给 then(( 的回调函数中:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

我怎么知道(即哪个文档指定(这个回调函数应该接受一个参数,这个参数对应于响应?

我的问题不仅限于 D3.js而是一般的 js 约定。

它必须由要向其传递回调的 API 方法记录。没有其他方法可以让你知道回调将被调用什么参数——或者什么时候调用它,它应该返回什么(如果有的话(,等等。

对于 D3 示例,它在delay文档中定义:

否则,如果 delay 是一个函数,则为每个选定的元素(按顺序(计算该函数,传递当前基准d和当前索引i,并将this上下文作为当前 DOM 元素。

对于您的 AngularJS 示例,then是一个 Promise 函数,记录在此处:

承诺 API

方法

  • then(successCallback, errorCallback, notifyCallback) – 无论承诺何时解决或将要解决或拒绝,一旦结果可用,就会异步调用其中一个成功或错误回调。使用单个参数调用回调:结果或拒绝原因。此外,在解决或拒绝承诺之前,可以调用零次或多次通知回调以提供进度指示。