如何使用函数(){在Javascript中使用回调函数

时间:2017-02-09 22:55:36

标签: javascript function callback

我知道如何进行核心回调和函数,但我想要这个用例:

   loadCSSFunction('/stylesheets/swiper.css',function (e){

        Execute code
        //Do some jquery call to a plugin for example

    });

如何构造loadCSSFunction以便能够形成这些函数,所以一旦动作发生(将CSS注入头部(我很好))然后我可以执行依赖于CSS注入的东西。 / p>

更新 请注意,这与CSS元素无关,它只是示例的一部分,与问题无关。如果我确实想要将其注入异步等,我会这样做。

函数调用:

   doSomethingWithFile('/folder/file.file',function (e){

        Execute code

    });

功能:

doSomethingWithFile: function(file){
      var mything = 'thing'+file;

    }

1 个答案:

答案 0 :(得分:1)

只需使用回调参数定义您的函数。

例如

function* preOrderGenerator(node) {
    yield node;
    for (let childNode of node.children)
        yield* preOrderGenerator(childNode);
}

你对文件做了些什么,与你的CSSloader没什么不同。

function loadCSSFunction(url, callback) {
   //do you CSS loading.
   //we have now loaded lets call the callback
   var e = 'something to pass to callback';
   callback(e);
}

现在我们可以使用我们的doSomethingWithFile ..

doSomethingWithFile: function(file, callback){
  var mything = 'thing'+file;
  //do what you want to do with file, 
  //again it doesn't matter if it's async / sync.
  //just call the callback when done..
  //eg below, readFileContents might be an async function
  readFileContents(file, function (err, data) {
    //normally async callbacks usually pass an err param
    //you should normally check for this too.
    if (err) callback(err); //if we have error pass it along.
    else callback(null, data); //here were sending our result back
  });
}