Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a promise-based version of the API #89

Merged
merged 1 commit into from
Jan 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ this point that is the only option. You can do without the `options` altogether.

The `cb` receives the typical `err` and `data` parameters.

If no `cb` parameter is provided, the `fetch()` method instead returns a promise that will resolve with the expected data.

### Specifications

Usage summary:
Expand Down
14 changes: 12 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,25 @@ function arrayify (obj) {
function Ctx (ctx) {
this.steps = ctx ? ctx.steps.concat([]) : [];
}
Ctx.prototype.fetch = function (options, cb) {
Ctx.prototype.fetch = async function (options, cb) {
if (typeof options === "function") {
cb = options;
options = {};
}
let promise;
if (typeof cb !== "function") {
let resolve, reject;
promise = new Promise((res, rej) => { resolve = res; reject = rej;});
cb = (err, result) => { if (err) return reject(err); return resolve(result) ; } ;
}

var url = exports.baseURL + this.steps.join("/")
, embed = options && options.embed
, request = makeRequest(url, embed)
, type = this.type || "item"
, key = this.linkKey
, embedKey = embed ? "_embedded" : "_links"
;

// what we want is to make one first request
// if it has all the data, just return that
// if not, then generate all the requests for each page, grab them all, collate the data, return that
Expand Down Expand Up @@ -86,6 +92,10 @@ Ctx.prototype.fetch = function (options, cb) {
}
);
});
if (!!promise) {
return promise;
}

};

// generates a function for the root list
Expand Down
8 changes: 8 additions & 0 deletions test/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,11 @@ describe("Specification Series", function() {
w3c.specificationseries(CSSCOLOR).specifications().fetch(listChecker(done, "CSS Color Module Level 3"));
});
});

describe("Promises API", function() {
it('returns a promise if no callback is set', async function() {
const groups = await w3c.groups().fetch();
expect(groups).to.be.an("array");
expect(groups.some(function (it) { return it.title === "Cascading Style Sheets (CSS) Working Group"; })).to.be.ok();
});
});