最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using Q library in browser - Stack Overflow

programmeradmin6浏览0评论

I need to use Q library (/) 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?

I need to use Q library (http://documentup./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?

Share Improve this question edited Sep 16, 2013 at 9:50 kryger 13.2k8 gold badges46 silver badges67 bronze badges asked Aug 20, 2013 at 5:31 user2365163user2365163 1331 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 14

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.

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

<script src="https://cdnjs.cloudflare./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/Uesyd/1/

发布评论

评论列表(0)

  1. 暂无评论