1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2026-01-03 23:22:30 +03:00

Add tiny promise wrapper.

This commit is contained in:
Kegan Dougal
2015-03-04 20:34:15 +00:00
parent 50f5279fb7
commit 18a684e0be
2 changed files with 38 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
"use strict";
console.log("Loading browser sdk");
// assign the global request module from browser-request.js
matrixcs.request(request);
var client = matrixcs.createClient("http://matrix.org");

37
lib/matrix-promise.js Normal file
View File

@@ -0,0 +1,37 @@
// Wraps all matrix.js API calls in Q promises.
//
// API calls usually accept callback functions. However, all API calls
// also return the result from request(opts, callback). It seems pointless
// to return from this since it is always "undefined". However, the "request"
// module is also injected into the SDK. This allows us to wrap the
// "request" module to return a promise, which is then passed all the
// way back up to the public facing API call.
//
// This wrapper is designed for Node.js development, but a similar
// technique can be trivially applied on the browser (e.g. for AngularJS)
"use strict";
var matrixcs = require("./matrix");
var request = require("request");
var q = require("q");
matrixcs.request(function(opts, callback) {
var defer = q.defer();
request(opts, function(err, response, body) {
// TODO possibly expose a responseHandler API
// to avoid duplicating the 400 check with the core lib.
if (err) {
defer.reject(err);
return;
}
if (response.statusCode >= 400) {
defer.reject(body);
}
else {
defer.resolve(body);
}
});
return defer.promise;
});
module.exports = matrixcs;