Using Q library in browser

守給你的承諾、 提交于 2019-12-04 13:46:15

问题


I need to use Q library (http://documentup.com/kriskowal/q/) in the browser. I would like to use RequireJS to load this library, but I don't have any idea how to do this. I know how to load my own module, but I can't do it with Q. It has some function:

(function (definition) { 
  //some another code here***
  // RequireJS
} else if (typeof define === "function" && define.amd) {
  define(definition);

How can I load Q and then use it in another module?


回答1:


You can simply load the Q library using a script statement in your HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.1.0/q.js"></script>

Then you can access it via the Q variable like so:

function square(x) {
    return x * x;
}
function plus1(x) {
    return x + 1;
}

Q.fcall(function () {return 4;})
.then(plus1)
.then(square)
.then(function(z) {
    alert("square of (value+1) = " + z);
});

See this running at http://jsfiddle.net/Uesyd/1/




回答2:


The proper AMD way of doing this would be (borrowed example code from @Eamonn O'Brien-Strain):

requirejs.config({
  paths: {
    Q: 'lib/q'
  }
});

function square(x) {
  return x * x;
}

function plus1(x) {
  return x + 1;
}

require(["Q"], function (q) {
  q.fcall(function () {
    return 4;
  })
    .then(plus1)
    .then(square)
    .then(function (z) {
      alert("square of (value+1) = " + z);
    });
});

This way Q doesn't leak to the global scope and it's easy to find all modules depending on this library.



来源:https://stackoverflow.com/questions/18327592/using-q-library-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!