簡體   English   中英

回調函數作為module.export參數

[英]callback function as a module.export parameter

誰能在下面的代碼中解釋callback()函數的作用? 這個回調函數從哪里來?

index.js

var _ = require('lodash');
var i18n = require('./lib/i18n');

var options = {
  stage: 'options:post:configuration'
};

/**
 * postprocess
 * @param  {Object}   params
 * @param  {Function} callback
 */
module.exports = function (params, callback) {
  'use strict';

  var grunt = params.grunt;

  grunt.verbose.subhead('Running:'.bold, '"assemble-contrib-i18n"');
  grunt.verbose.writeln('Stage:  '.bold, '"' + params.stage + '"\n');

  var opts = params.assemble.options.i18n;
  grunt.verbose.writeln('Options: '.bold, require('util').inspect(opts));

  if (opts) {
    var o = {};
    var data = opts.data;
    var templates = opts.templates;
    var languages = opts.languages;

    if (templates) {
      o.templates = templates;
    }

    if (languages) {
      o.languages = languages;
    }
//data = path to a json file containing a list of languages, o = templates & languages
    var pages = i18n(data, o);

    grunt.verbose.writeln('Pages: '.bold, require('util').inspect(pages));
    params.assemble.options.pages = _.extend({}, (params.assemble.options.pages || {}), pages);

  }

  callback();
};

module.exports.options = options;

index.js文件的使用位置位於gruntfile.js文件中

  "with-plugin": {
    options: {
      plugins: ['./index.js'],
      i18n: {
        data: ['test/fixtures/data/i18n.json'],
        templates: ['test/fixtures/templates/*.hbs']
      }
    },
    dest: 'test/actual/with-plugin/',
    src: '!*.*'
  },

那么這里的回調函數是什么?

定義的函數(接受回調作為參數)是當腳本requires此模塊時導入的值。 因此,回調由調用腳本提供:

require('someModule')(someParams, myCallback);
// which is the same as:
var func = require('someModule');
func(someParams, myCallback);

在您提供的代碼中,回調沒有什么特別的,它只是在函數末尾執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM