1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-12-01 04:43:29 +03:00

Merge pull request #490 from matrix-org/rav/bluebird

Switch matrix-js-sdk to bluebird
This commit is contained in:
Richard van der Hoff
2017-07-12 23:34:40 +01:00
committed by GitHub
36 changed files with 244 additions and 245 deletions

View File

@@ -49,9 +49,9 @@
], ],
"dependencies": { "dependencies": {
"another-json": "^0.2.0", "another-json": "^0.2.0",
"bluebird": "^3.5.0",
"browser-request": "^0.3.3", "browser-request": "^0.3.3",
"content-type": "^1.0.2", "content-type": "^1.0.2",
"q": "^1.4.1",
"regenerator-runtime": "^0.10.5", "regenerator-runtime": "^0.10.5",
"request": "^2.53.0" "request": "^2.53.0"
}, },

View File

@@ -24,7 +24,7 @@ import sdk from '..';
import testUtils from './test-utils'; import testUtils from './test-utils';
import MockHttpBackend from 'matrix-mock-request'; import MockHttpBackend from 'matrix-mock-request';
import expect from 'expect'; import expect from 'expect';
import q from 'q'; import Promise from 'bluebird';
/** /**
* Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient * Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient
@@ -118,7 +118,7 @@ TestClient.prototype.expectDeviceKeyUpload = function() {
TestClient.prototype.awaitOneTimeKeyUpload = function() { TestClient.prototype.awaitOneTimeKeyUpload = function() {
if (Object.keys(this.oneTimeKeys).length != 0) { if (Object.keys(this.oneTimeKeys).length != 0) {
// already got one-time keys // already got one-time keys
return q(this.oneTimeKeys); return Promise.resolve(this.oneTimeKeys);
} }
this.httpBackend.when("POST", "/keys/upload") this.httpBackend.when("POST", "/keys/upload")
@@ -195,7 +195,7 @@ TestClient.prototype.getSigningKey = function() {
*/ */
TestClient.prototype.flushSync = function() { TestClient.prototype.flushSync = function() {
console.log(`${this}: flushSync`); console.log(`${this}: flushSync`);
return q.all([ return Promise.all([
this.httpBackend.flush('/sync', 1), this.httpBackend.flush('/sync', 1),
testUtils.syncPromise(this.client), testUtils.syncPromise(this.client),
]); ]);

View File

@@ -31,7 +31,7 @@ import '../olm-loader';
import expect from 'expect'; import expect from 'expect';
const sdk = require("../.."); const sdk = require("../..");
const q = require("q"); import Promise from 'bluebird';
const utils = require("../../lib/utils"); const utils = require("../../lib/utils");
const testUtils = require("../test-utils"); const testUtils = require("../test-utils");
const TestClient = require('../TestClient').default; const TestClient = require('../TestClient').default;
@@ -50,7 +50,7 @@ let bobMessages;
function bobUploadsDeviceKeys() { function bobUploadsDeviceKeys() {
bobTestClient.expectDeviceKeyUpload(); bobTestClient.expectDeviceKeyUpload();
return q.all([ return Promise.all([
bobTestClient.client.uploadKeys(), bobTestClient.client.uploadKeys(),
bobTestClient.httpBackend.flush(), bobTestClient.httpBackend.flush(),
]).then(() => { ]).then(() => {
@@ -157,7 +157,7 @@ function aliDownloadsKeys() {
// check that the localStorage is updated as we expect (not sure this is // check that the localStorage is updated as we expect (not sure this is
// an integration test, but meh) // an integration test, but meh)
return q.all([p1, p2]).then(function() { return Promise.all([p1, p2]).then(function() {
const devices = aliTestClient.storage.getEndToEndDevicesForUser(bobUserId); const devices = aliTestClient.storage.getEndToEndDevicesForUser(bobUserId);
expect(devices[bobDeviceId].keys).toEqual(bobTestClient.deviceKeys.keys); expect(devices[bobDeviceId].keys).toEqual(bobTestClient.deviceKeys.keys);
expect(devices[bobDeviceId].verified). expect(devices[bobDeviceId].verified).
@@ -188,7 +188,7 @@ function bobEnablesEncryption() {
* @return {promise} which resolves to the ciphertext for Bob's device. * @return {promise} which resolves to the ciphertext for Bob's device.
*/ */
function aliSendsFirstMessage() { function aliSendsFirstMessage() {
return q.all([ return Promise.all([
sendMessage(aliTestClient.client), sendMessage(aliTestClient.client),
expectAliQueryKeys() expectAliQueryKeys()
.then(expectAliClaimKeys) .then(expectAliClaimKeys)
@@ -205,7 +205,7 @@ function aliSendsFirstMessage() {
* @return {promise} which resolves to the ciphertext for Bob's device. * @return {promise} which resolves to the ciphertext for Bob's device.
*/ */
function aliSendsMessage() { function aliSendsMessage() {
return q.all([ return Promise.all([
sendMessage(aliTestClient.client), sendMessage(aliTestClient.client),
expectAliSendMessageRequest(), expectAliSendMessageRequest(),
]).spread(function(_, ciphertext) { ]).spread(function(_, ciphertext) {
@@ -220,7 +220,7 @@ function aliSendsMessage() {
* @return {promise} which resolves to the ciphertext for Ali's device. * @return {promise} which resolves to the ciphertext for Ali's device.
*/ */
function bobSendsReplyMessage() { function bobSendsReplyMessage() {
return q.all([ return Promise.all([
sendMessage(bobTestClient.client), sendMessage(bobTestClient.client),
expectBobQueryKeys() expectBobQueryKeys()
.then(expectBobSendMessageRequest), .then(expectBobSendMessageRequest),
@@ -269,7 +269,7 @@ function sendMessage(client) {
function expectSendMessageRequest(httpBackend) { function expectSendMessageRequest(httpBackend) {
const path = "/send/m.room.encrypted/"; const path = "/send/m.room.encrypted/";
const deferred = q.defer(); const deferred = Promise.defer();
httpBackend.when("PUT", path).respond(200, function(path, content) { httpBackend.when("PUT", path).respond(200, function(path, content) {
deferred.resolve(content); deferred.resolve(content);
return { return {
@@ -317,7 +317,7 @@ function recvMessage(httpBackend, client, sender, message) {
}, },
}; };
httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.when("GET", "/sync").respond(200, syncData);
const deferred = q.defer(); const deferred = Promise.defer();
const onEvent = function(event) { const onEvent = function(event) {
console.log(client.credentials.userId + " received event", console.log(client.credentials.userId + " received event",
event); event);
@@ -406,19 +406,19 @@ describe("MatrixClient crypto", function() {
}); });
it("Bob uploads device keys", function() { it("Bob uploads device keys", function() {
return q() return Promise.resolve()
.then(bobUploadsDeviceKeys); .then(bobUploadsDeviceKeys);
}); });
it("Ali downloads Bobs device keys", function(done) { it("Ali downloads Bobs device keys", function(done) {
q() Promise.resolve()
.then(bobUploadsDeviceKeys) .then(bobUploadsDeviceKeys)
.then(aliDownloadsKeys) .then(aliDownloadsKeys)
.nodeify(done); .nodeify(done);
}); });
it("Ali gets keys with an invalid signature", function(done) { it("Ali gets keys with an invalid signature", function(done) {
q() Promise.resolve()
.then(bobUploadsDeviceKeys) .then(bobUploadsDeviceKeys)
.then(function() { .then(function() {
// tamper bob's keys // tamper bob's keys
@@ -426,7 +426,7 @@ describe("MatrixClient crypto", function() {
expect(bobDeviceKeys.keys["curve25519:" + bobDeviceId]).toBeTruthy(); expect(bobDeviceKeys.keys["curve25519:" + bobDeviceId]).toBeTruthy();
bobDeviceKeys.keys["curve25519:" + bobDeviceId] += "abc"; bobDeviceKeys.keys["curve25519:" + bobDeviceId] += "abc";
return q.all([ return Promise.all([
aliTestClient.client.downloadKeys([bobUserId]), aliTestClient.client.downloadKeys([bobUserId]),
expectAliQueryKeys(), expectAliQueryKeys(),
]); ]);
@@ -467,7 +467,7 @@ describe("MatrixClient crypto", function() {
return {device_keys: result}; return {device_keys: result};
}); });
q.all([ Promise.all([
aliTestClient.client.downloadKeys([bobUserId, eveUserId]), aliTestClient.client.downloadKeys([bobUserId, eveUserId]),
aliTestClient.httpBackend.flush("/keys/query", 1), aliTestClient.httpBackend.flush("/keys/query", 1),
]).then(function() { ]).then(function() {
@@ -504,7 +504,7 @@ describe("MatrixClient crypto", function() {
return {device_keys: result}; return {device_keys: result};
}); });
q.all([ Promise.all([
aliTestClient.client.downloadKeys([bobUserId]), aliTestClient.client.downloadKeys([bobUserId]),
aliTestClient.httpBackend.flush("/keys/query", 1), aliTestClient.httpBackend.flush("/keys/query", 1),
]).then(function() { ]).then(function() {
@@ -515,7 +515,7 @@ describe("MatrixClient crypto", function() {
it("Bob starts his client and uploads device keys and one-time keys", function() { it("Bob starts his client and uploads device keys and one-time keys", function() {
return q() return Promise.resolve()
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => bobTestClient.awaitOneTimeKeyUpload()) .then(() => bobTestClient.awaitOneTimeKeyUpload())
.then((keys) => { .then((keys) => {
@@ -525,7 +525,7 @@ describe("MatrixClient crypto", function() {
}); });
it("Ali sends a message", function(done) { it("Ali sends a message", function(done) {
q() Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
@@ -535,7 +535,7 @@ describe("MatrixClient crypto", function() {
}); });
it("Bob receives a message", function(done) { it("Bob receives a message", function(done) {
q() Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
@@ -546,7 +546,7 @@ describe("MatrixClient crypto", function() {
}); });
it("Bob receives a message with a bogus sender", function(done) { it("Bob receives a message with a bogus sender", function(done) {
q() Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
@@ -576,7 +576,7 @@ describe("MatrixClient crypto", function() {
}; };
bobTestClient.httpBackend.when("GET", "/sync").respond(200, syncData); bobTestClient.httpBackend.when("GET", "/sync").respond(200, syncData);
const deferred = q.defer(); const deferred = Promise.defer();
const onEvent = function(event) { const onEvent = function(event) {
console.log(bobUserId + " received event", console.log(bobUserId + " received event",
event); event);
@@ -603,7 +603,7 @@ describe("MatrixClient crypto", function() {
}); });
it("Ali blocks Bob's device", function(done) { it("Ali blocks Bob's device", function(done) {
q() Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
@@ -617,12 +617,12 @@ describe("MatrixClient crypto", function() {
// no unblocked devices, so the ciphertext should be empty // no unblocked devices, so the ciphertext should be empty
expect(sentContent.ciphertext).toEqual({}); expect(sentContent.ciphertext).toEqual({});
}); });
return q.all([p1, p2]); return Promise.all([p1, p2]);
}).nodeify(done); }).nodeify(done);
}); });
it("Bob receives two pre-key messages", function(done) { it("Bob receives two pre-key messages", function(done) {
q() Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
@@ -635,7 +635,7 @@ describe("MatrixClient crypto", function() {
}); });
it("Bob replies to the message", function() { it("Bob replies to the message", function() {
return q() return Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => bobTestClient.start()) .then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
@@ -652,7 +652,7 @@ describe("MatrixClient crypto", function() {
it("Ali does a key query when encryption is enabled", function() { it("Ali does a key query when encryption is enabled", function() {
// enabling encryption in the room should make alice download devices // enabling encryption in the room should make alice download devices
// for both members. // for both members.
return q() return Promise.resolve()
.then(() => aliTestClient.start()) .then(() => aliTestClient.start())
.then(() => firstSync(aliTestClient)) .then(() => firstSync(aliTestClient))
.then(() => { .then(() => {

View File

@@ -1,6 +1,6 @@
"use strict"; "use strict";
import 'source-map-support/register'; import 'source-map-support/register';
const q = require("q"); import Promise from 'bluebird';
const sdk = require("../.."); const sdk = require("../..");
const HttpBackend = require("matrix-mock-request"); const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
@@ -82,7 +82,7 @@ function startClient(httpBackend, client) {
client.startClient(); client.startClient();
// set up a promise which will resolve once the client is initialised // set up a promise which will resolve once the client is initialised
const deferred = q.defer(); const deferred = Promise.defer();
client.on("sync", function(state) { client.on("sync", function(state) {
console.log("sync", state); console.log("sync", state);
if (state != "SYNCING") { if (state != "SYNCING") {
@@ -91,7 +91,7 @@ function startClient(httpBackend, client) {
deferred.resolve(); deferred.resolve();
}); });
return q.all([ return Promise.all([
httpBackend.flushAllExpected(), httpBackend.flushAllExpected(),
deferred.promise, deferred.promise,
]); ]);
@@ -205,7 +205,7 @@ describe("getEventTimeline support", function() {
}).then(() => { }).then(() => {
// the sync isn't processed immediately; give the promise chain // the sync isn't processed immediately; give the promise chain
// a chance to complete. // a chance to complete.
return q.delay(0); return Promise.delay(0);
}).then(function() { }).then(function() {
expect(room.timeline.length).toEqual(1); expect(room.timeline.length).toEqual(1);
expect(room.timeline[0].event).toEqual(EVENTS[1]); expect(room.timeline[0].event).toEqual(EVENTS[1]);
@@ -266,7 +266,7 @@ describe("MatrixClient event timelines", function() {
}; };
}); });
return q.all([ return Promise.all([
client.getEventTimeline(timelineSet, "event1:bar").then(function(tl) { client.getEventTimeline(timelineSet, "event1:bar").then(function(tl) {
expect(tl.getEvents().length).toEqual(4); expect(tl.getEvents().length).toEqual(4);
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
@@ -346,7 +346,7 @@ describe("MatrixClient event timelines", function() {
}; };
}); });
const deferred = q.defer(); const deferred = Promise.defer();
client.on("sync", function() { client.on("sync", function() {
client.getEventTimeline(timelineSet, EVENTS[2].event_id, client.getEventTimeline(timelineSet, EVENTS[2].event_id,
).then(function(tl) { ).then(function(tl) {
@@ -362,7 +362,7 @@ describe("MatrixClient event timelines", function() {
(e) => deferred.reject(e)); (e) => deferred.reject(e));
}); });
return q.all([ return Promise.all([
httpBackend.flushAllExpected(), httpBackend.flushAllExpected(),
deferred.promise, deferred.promise,
]); ]);
@@ -429,7 +429,7 @@ describe("MatrixClient event timelines", function() {
let tl0; let tl0;
let tl3; let tl3;
return q.all([ return Promise.all([
client.getEventTimeline(timelineSet, EVENTS[0].event_id, client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl) { ).then(function(tl) {
expect(tl.getEvents().length).toEqual(1); expect(tl.getEvents().length).toEqual(1);
@@ -480,7 +480,7 @@ describe("MatrixClient event timelines", function() {
}; };
}); });
return q.all([ return Promise.all([
client.getEventTimeline(timelineSet, "event1", client.getEventTimeline(timelineSet, "event1",
).then(function(tl) { ).then(function(tl) {
// could do with a fail() // could do with a fail()
@@ -525,7 +525,7 @@ describe("MatrixClient event timelines", function() {
}); });
let tl; let tl;
return q.all([ return Promise.all([
client.getEventTimeline(timelineSet, EVENTS[0].event_id, client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) { ).then(function(tl0) {
tl = tl0; tl = tl0;
@@ -577,7 +577,7 @@ describe("MatrixClient event timelines", function() {
}); });
let tl; let tl;
return q.all([ return Promise.all([
client.getEventTimeline(timelineSet, EVENTS[0].event_id, client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) { ).then(function(tl0) {
tl = tl0; tl = tl0;
@@ -634,7 +634,7 @@ describe("MatrixClient event timelines", function() {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
return q.all([ return Promise.all([
client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) { client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) {
expect(res.event_id).toEqual(event.event_id); expect(res.event_id).toEqual(event.event_id);
return client.getEventTimeline(timelineSet, event.event_id); return client.getEventTimeline(timelineSet, event.event_id);
@@ -644,7 +644,7 @@ describe("MatrixClient event timelines", function() {
expect(tl.getEvents()[1].getContent().body).toEqual("a body"); expect(tl.getEvents()[1].getContent().body).toEqual("a body");
// now let the sync complete, and check it again // now let the sync complete, and check it again
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]); ]);
@@ -663,7 +663,7 @@ describe("MatrixClient event timelines", function() {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
return q.all([ return Promise.all([
// initiate the send, and set up checks to be done when it completes // initiate the send, and set up checks to be done when it completes
// - but note that it won't complete until after the /sync does, below. // - but note that it won't complete until after the /sync does, below.
client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) { client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) {
@@ -676,7 +676,7 @@ describe("MatrixClient event timelines", function() {
expect(tl.getEvents()[1].getContent().body).toEqual("a body"); expect(tl.getEvents()[1].getContent().body).toEqual("a body");
}), }),
q.all([ Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {

View File

@@ -6,7 +6,7 @@ const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
import expect from 'expect'; import expect from 'expect';
import q from 'q'; import Promise from 'bluebird';
describe("MatrixClient opts", function() { describe("MatrixClient opts", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
@@ -114,7 +114,7 @@ describe("MatrixClient opts", function() {
httpBackend.flush("/pushrules", 1).then(function() { httpBackend.flush("/pushrules", 1).then(function() {
return httpBackend.flush("/filter", 1); return httpBackend.flush("/filter", 1);
}).then(function() { }).then(function() {
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]); ]);

View File

@@ -5,7 +5,7 @@ const EventStatus = sdk.EventStatus;
const HttpBackend = require("matrix-mock-request"); const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils"); const utils = require("../test-utils");
import q from 'q'; import Promise from 'bluebird';
import expect from 'expect'; import expect from 'expect';
describe("MatrixClient room timelines", function() { describe("MatrixClient room timelines", function() {
@@ -394,7 +394,7 @@ describe("MatrixClient room timelines", function() {
]; ];
setNextSyncData(eventData); setNextSyncData(eventData);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(() => { ]).then(() => {
@@ -409,7 +409,7 @@ describe("MatrixClient room timelines", function() {
}); });
httpBackend.flush("/messages", 1); httpBackend.flush("/messages", 1);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {
@@ -436,12 +436,12 @@ describe("MatrixClient room timelines", function() {
eventData[1].__prev_event = USER_MEMBERSHIP_EVENT; eventData[1].__prev_event = USER_MEMBERSHIP_EVENT;
setNextSyncData(eventData); setNextSyncData(eventData);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(() => { ]).then(() => {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {
@@ -462,7 +462,7 @@ describe("MatrixClient room timelines", function() {
secondRoomNameEvent.__prev_event = ROOM_NAME_EVENT; secondRoomNameEvent.__prev_event = ROOM_NAME_EVENT;
setNextSyncData([secondRoomNameEvent]); setNextSyncData([secondRoomNameEvent]);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(() => { ]).then(() => {
@@ -472,7 +472,7 @@ describe("MatrixClient room timelines", function() {
nameEmitCount += 1; nameEmitCount += 1;
}); });
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {
@@ -487,7 +487,7 @@ describe("MatrixClient room timelines", function() {
thirdRoomNameEvent.__prev_event = secondRoomNameEvent; thirdRoomNameEvent.__prev_event = secondRoomNameEvent;
setNextSyncData([thirdRoomNameEvent]); setNextSyncData([thirdRoomNameEvent]);
httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA); httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]); ]);
@@ -513,12 +513,12 @@ describe("MatrixClient room timelines", function() {
eventData[1].__prev_event = null; eventData[1].__prev_event = null;
setNextSyncData(eventData); setNextSyncData(eventData);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(() => { ]).then(() => {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {
@@ -544,14 +544,14 @@ describe("MatrixClient room timelines", function() {
setNextSyncData(eventData); setNextSyncData(eventData);
NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true; NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true;
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(() => { ]).then(() => {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
httpBackend.flush("/messages", 1); httpBackend.flush("/messages", 1);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {
@@ -577,7 +577,7 @@ describe("MatrixClient room timelines", function() {
setNextSyncData(eventData); setNextSyncData(eventData);
NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true; NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true;
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(() => { ]).then(() => {
@@ -590,7 +590,7 @@ describe("MatrixClient room timelines", function() {
}); });
httpBackend.flush("/messages", 1); httpBackend.flush("/messages", 1);
return q.all([ return Promise.all([
httpBackend.flush("/sync", 1), httpBackend.flush("/sync", 1),
utils.syncPromise(client), utils.syncPromise(client),
]).then(function() { ]).then(function() {

View File

@@ -7,7 +7,7 @@ const MatrixEvent = sdk.MatrixEvent;
const EventTimeline = sdk.EventTimeline; const EventTimeline = sdk.EventTimeline;
import expect from 'expect'; import expect from 'expect';
import q from 'q'; import Promise from 'bluebird';
describe("MatrixClient syncing", function() { describe("MatrixClient syncing", function() {
const baseUrl = "http://localhost.or.something"; const baseUrl = "http://localhost.or.something";
@@ -634,7 +634,7 @@ describe("MatrixClient syncing", function() {
include_leave: true }}); include_leave: true }});
}).respond(200, { filter_id: "another_id" }); }).respond(200, { filter_id: "another_id" });
const defer = q.defer(); const defer = Promise.defer();
httpBackend.when("GET", "/sync").check(function(req) { httpBackend.when("GET", "/sync").check(function(req) {
expect(req.queryParams.filter).toEqual("another_id"); expect(req.queryParams.filter).toEqual("another_id");
@@ -645,7 +645,7 @@ describe("MatrixClient syncing", function() {
// first flush the filter request; this will make syncLeftRooms // first flush the filter request; this will make syncLeftRooms
// make its /sync call // make its /sync call
return q.all([ return Promise.all([
httpBackend.flush("/filter").then(function() { httpBackend.flush("/filter").then(function() {
// flush the syncs // flush the syncs
return httpBackend.flushAllExpected(); return httpBackend.flushAllExpected();
@@ -679,7 +679,7 @@ describe("MatrixClient syncing", function() {
httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.when("GET", "/sync").respond(200, syncData);
return q.all([ return Promise.all([
client.syncLeftRooms().then(function() { client.syncLeftRooms().then(function() {
const room = client.getRoom(roomTwo); const room = client.getRoom(roomTwo);
const tok = room.getLiveTimeline().getPaginationToken( const tok = room.getLiveTimeline().getPaginationToken(

View File

@@ -17,7 +17,7 @@ limitations under the License.
"use strict"; "use strict";
const anotherjson = require('another-json'); const anotherjson = require('another-json');
const q = require('q'); import Promise from 'bluebird';
import expect from 'expect'; import expect from 'expect';
const utils = require('../../lib/utils'); const utils = require('../../lib/utils');
@@ -506,7 +506,7 @@ describe("megolm", function() {
200, getTestKeysQueryResponse('@bob:xyz'), 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test').then(() => { aliceTestClient.client.sendTextMessage(ROOM_ID, 'test').then(() => {
throw new Error("sendTextMessage failed on an unknown device"); throw new Error("sendTextMessage failed on an unknown device");
}, (e) => { }, (e) => {
@@ -552,7 +552,7 @@ describe("megolm", function() {
const room = aliceTestClient.client.getRoom(ROOM_ID); const room = aliceTestClient.client.getRoom(ROOM_ID);
const pendingMsg = room.getPendingEvents()[0]; const pendingMsg = room.getPendingEvents()[0];
return q.all([ return Promise.all([
aliceTestClient.client.resendEvent(pendingMsg, room), aliceTestClient.client.resendEvent(pendingMsg, room),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]); ]);
@@ -574,7 +574,7 @@ describe("megolm", function() {
}, },
}); });
return q.all([ return Promise.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']), aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flush('/keys/query', 1), aliceTestClient.httpBackend.flush('/keys/query', 1),
]); ]);
@@ -587,7 +587,7 @@ describe("megolm", function() {
event_id: '$event_id', event_id: '$event_id',
}); });
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'), aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]); ]);
@@ -619,7 +619,7 @@ describe("megolm", function() {
200, getTestKeysQueryResponse('@bob:xyz'), 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return q.all([ return Promise.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']), aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flush('/keys/query', 1), aliceTestClient.httpBackend.flush('/keys/query', 1),
]); ]);
@@ -634,7 +634,7 @@ describe("megolm", function() {
event_id: '$event_id', event_id: '$event_id',
}); });
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'), aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]); ]);
@@ -670,7 +670,7 @@ describe("megolm", function() {
200, getTestKeysQueryResponse('@bob:xyz'), 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return q.all([ return Promise.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']), aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]).then((keys) => { ]).then((keys) => {
@@ -703,7 +703,7 @@ describe("megolm", function() {
}; };
}); });
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'), aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]); ]);
@@ -722,7 +722,7 @@ describe("megolm", function() {
}; };
}); });
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test2'), aliceTestClient.client.sendTextMessage(ROOM_ID, 'test2'),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]); ]);
@@ -824,7 +824,7 @@ describe("megolm", function() {
}; };
}); });
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'), aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(), aliceTestClient.httpBackend.flushAllExpected(),
]); ]);
@@ -875,7 +875,7 @@ describe("megolm", function() {
return aliceTestClient.httpBackend.flushAllExpected(); return aliceTestClient.httpBackend.flushAllExpected();
}).then(function() { }).then(function() {
return q.all([downloadPromise, sendPromise]); return Promise.all([downloadPromise, sendPromise]);
}); });
}); });
@@ -903,7 +903,7 @@ describe("megolm", function() {
aliceTestClient.httpBackend.when('PUT', '/send/').respond( aliceTestClient.httpBackend.when('PUT', '/send/').respond(
200, {event_id: '$event1'}); 200, {event_id: '$event1'});
return q.all([ return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'), aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flush('/keys/query', 1).then( aliceTestClient.httpBackend.flush('/keys/query', 1).then(
() => aliceTestClient.httpBackend.flush('/send/', 1), () => aliceTestClient.httpBackend.flush('/send/', 1),

View File

@@ -1,6 +1,6 @@
"use strict"; "use strict";
import expect from 'expect'; import expect from 'expect';
import q from 'q'; import Promise from 'bluebird';
// load olm before the sdk if possible // load olm before the sdk if possible
import './olm-loader'; import './olm-loader';
@@ -15,7 +15,7 @@ const MatrixEvent = sdk.MatrixEvent;
* @return {Promise} Resolves once the client has emitted a SYNCING event * @return {Promise} Resolves once the client has emitted a SYNCING event
*/ */
module.exports.syncPromise = function(client) { module.exports.syncPromise = function(client) {
const def = q.defer(); const def = Promise.defer();
const cb = (state) => { const cb = (state) => {
if (state == 'SYNCING') { if (state == 'SYNCING') {
def.resolve(); def.resolve();

View File

@@ -5,7 +5,7 @@ import testUtils from '../../test-utils';
import utils from '../../../lib/utils'; import utils from '../../../lib/utils';
import expect from 'expect'; import expect from 'expect';
import q from 'q'; import Promise from 'bluebird';
const signedDeviceList = { const signedDeviceList = {
"failures": {}, "failures": {},
@@ -64,7 +64,7 @@ describe('DeviceList', function() {
dl.startTrackingDeviceList('@test1:sw1v.org'); dl.startTrackingDeviceList('@test1:sw1v.org');
const queryDefer1 = q.defer(); const queryDefer1 = Promise.defer();
downloadSpy.andReturn(queryDefer1.promise); downloadSpy.andReturn(queryDefer1.promise);
const prom1 = dl.refreshOutdatedDeviceLists(); const prom1 = dl.refreshOutdatedDeviceLists();
@@ -83,7 +83,7 @@ describe('DeviceList', function() {
dl.startTrackingDeviceList('@test1:sw1v.org'); dl.startTrackingDeviceList('@test1:sw1v.org');
const queryDefer1 = q.defer(); const queryDefer1 = Promise.defer();
downloadSpy.andReturn(queryDefer1.promise); downloadSpy.andReturn(queryDefer1.promise);
const prom1 = dl.refreshOutdatedDeviceLists(); const prom1 = dl.refreshOutdatedDeviceLists();
@@ -91,7 +91,7 @@ describe('DeviceList', function() {
downloadSpy.reset(); downloadSpy.reset();
// outdated notif arrives while the request is in flight. // outdated notif arrives while the request is in flight.
const queryDefer2 = q.defer(); const queryDefer2 = Promise.defer();
downloadSpy.andReturn(queryDefer2.promise); downloadSpy.andReturn(queryDefer2.promise);
dl.invalidateUserDeviceList('@test1:sw1v.org'); dl.invalidateUserDeviceList('@test1:sw1v.org');
@@ -110,7 +110,7 @@ describe('DeviceList', function() {
console.log("Creating new devicelist to simulate app reload"); console.log("Creating new devicelist to simulate app reload");
downloadSpy.reset(); downloadSpy.reset();
const dl2 = createTestDeviceList(); const dl2 = createTestDeviceList();
const queryDefer3 = q.defer(); const queryDefer3 = Promise.defer();
downloadSpy.andReturn(queryDefer3.promise); downloadSpy.andReturn(queryDefer3.promise);
const prom3 = dl2.refreshOutdatedDeviceLists(); const prom3 = dl2.refreshOutdatedDeviceLists();

View File

@@ -5,7 +5,7 @@ try {
} }
import expect from 'expect'; import expect from 'expect';
import q from 'q'; import Promise from 'bluebird';
import sdk from '../../../..'; import sdk from '../../../..';
import algorithms from '../../../../lib/crypto/algorithms'; import algorithms from '../../../../lib/crypto/algorithms';
@@ -125,7 +125,7 @@ describe("MegolmDecryption", function() {
const deviceInfo = {}; const deviceInfo = {};
mockCrypto.getStoredDevice.andReturn(deviceInfo); mockCrypto.getStoredDevice.andReturn(deviceInfo);
mockOlmLib.ensureOlmSessionsForDevices.andReturn( mockOlmLib.ensureOlmSessionsForDevices.andReturn(
q({'@alice:foo': {'alidevice': { Promise.resolve({'@alice:foo': {'alidevice': {
sessionId: 'alisession', sessionId: 'alisession',
}}}), }}}),
); );
@@ -136,7 +136,7 @@ describe("MegolmDecryption", function() {
megolmDecryption.shareKeysWithDevice(keyRequest); megolmDecryption.shareKeysWithDevice(keyRequest);
// it's asynchronous, so we have to wait a bit // it's asynchronous, so we have to wait a bit
return q.delay(1).then(() => { return Promise.delay(1).then(() => {
// check that it called encryptMessageForDevice with // check that it called encryptMessageForDevice with
// appropriate args. // appropriate args.
expect(mockOlmLib.encryptMessageForDevice.calls.length) expect(mockOlmLib.encryptMessageForDevice.calls.length)

View File

@@ -16,7 +16,7 @@ limitations under the License.
"use strict"; "use strict";
import 'source-map-support/register'; import 'source-map-support/register';
const q = require("q"); import Promise from 'bluebird';
const sdk = require("../.."); const sdk = require("../..");
const utils = require("../test-utils"); const utils = require("../test-utils");
@@ -81,7 +81,7 @@ describe("InteractiveAuth", function() {
type: "logintype", type: "logintype",
foo: "bar", foo: "bar",
}); });
return q(requestRes); return Promise.resolve(requestRes);
}); });
ia.attemptAuth().then(function(res) { ia.attemptAuth().then(function(res) {
@@ -138,7 +138,7 @@ describe("InteractiveAuth", function() {
type: "logintype", type: "logintype",
foo: "bar", foo: "bar",
}); });
return q(requestRes); return Promise.resolve(requestRes);
}); });
ia.submitAuthDict({ ia.submitAuthDict({

View File

@@ -1,6 +1,6 @@
"use strict"; "use strict";
import 'source-map-support/register'; import 'source-map-support/register';
const q = require("q"); import Promise from 'bluebird';
const sdk = require("../.."); const sdk = require("../..");
const MatrixClient = sdk.MatrixClient; const MatrixClient = sdk.MatrixClient;
const utils = require("../test-utils"); const utils = require("../test-utils");
@@ -62,7 +62,7 @@ describe("MatrixClient", function() {
let pendingLookup = null; let pendingLookup = null;
function httpReq(cb, method, path, qp, data, prefix) { function httpReq(cb, method, path, qp, data, prefix) {
if (path === KEEP_ALIVE_PATH && acceptKeepalives) { if (path === KEEP_ALIVE_PATH && acceptKeepalives) {
return q(); return Promise.resolve();
} }
const next = httpLookups.shift(); const next = httpLookups.shift();
const logLine = ( const logLine = (
@@ -84,7 +84,7 @@ describe("MatrixClient", function() {
); );
} }
pendingLookup = { pendingLookup = {
promise: q.defer().promise, promise: Promise.defer().promise,
method: method, method: method,
path: path, path: path,
}; };
@@ -109,7 +109,7 @@ describe("MatrixClient", function() {
} }
if (next.error) { if (next.error) {
return q.reject({ return Promise.reject({
errcode: next.error.errcode, errcode: next.error.errcode,
httpStatus: next.error.httpStatus, httpStatus: next.error.httpStatus,
name: next.error.errcode, name: next.error.errcode,
@@ -117,10 +117,10 @@ describe("MatrixClient", function() {
data: next.error, data: next.error,
}); });
} }
return q(next.data); return Promise.resolve(next.data);
} }
expect(true).toBe(false, "Expected different request. " + logLine); expect(true).toBe(false, "Expected different request. " + logLine);
return q.defer().promise; return Promise.defer().promise;
} }
beforeEach(function() { beforeEach(function() {
@@ -136,8 +136,8 @@ describe("MatrixClient", function() {
"getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter", "getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter",
"getSyncAccumulator", "startup", "deleteAllData", "getSyncAccumulator", "startup", "deleteAllData",
].reduce((r, k) => { r[k] = expect.createSpy(); return r; }, {}); ].reduce((r, k) => { r[k] = expect.createSpy(); return r; }, {});
store.getSavedSync = expect.createSpy().andReturn(q(null)); store.getSavedSync = expect.createSpy().andReturn(Promise.resolve(null));
store.setSyncData = expect.createSpy().andReturn(q(null)); store.setSyncData = expect.createSpy().andReturn(Promise.resolve(null));
client = new MatrixClient({ client = new MatrixClient({
baseUrl: "https://my.home.server", baseUrl: "https://my.home.server",
idBaseUrl: identityServerUrl, idBaseUrl: identityServerUrl,
@@ -174,10 +174,10 @@ describe("MatrixClient", function() {
// a DIFFERENT test (pollution between tests!) - we return unresolved // a DIFFERENT test (pollution between tests!) - we return unresolved
// promises to stop the client from continuing to run. // promises to stop the client from continuing to run.
client._http.authedRequest.andCall(function() { client._http.authedRequest.andCall(function() {
return q.defer().promise; return Promise.defer().promise;
}); });
client._http.authedRequestWithPrefix.andCall(function() { client._http.authedRequestWithPrefix.andCall(function() {
return q.defer().promise; return Promise.defer().promise;
}); });
}); });

View File

@@ -2,7 +2,7 @@
/* eslint new-cap: "off" */ /* eslint new-cap: "off" */
import 'source-map-support/register'; import 'source-map-support/register';
const q = require("q"); import Promise from 'bluebird';
const sdk = require("../.."); const sdk = require("../..");
const MatrixScheduler = sdk.MatrixScheduler; const MatrixScheduler = sdk.MatrixScheduler;
const MatrixError = sdk.MatrixError; const MatrixError = sdk.MatrixError;
@@ -41,7 +41,7 @@ describe("MatrixScheduler", function() {
}); });
retryFn = null; retryFn = null;
queueFn = null; queueFn = null;
defer = q.defer(); defer = Promise.defer();
}); });
afterEach(function() { afterEach(function() {
@@ -55,8 +55,8 @@ describe("MatrixScheduler", function() {
queueFn = function() { queueFn = function() {
return "one_big_queue"; return "one_big_queue";
}; };
const deferA = q.defer(); const deferA = Promise.defer();
const deferB = q.defer(); const deferB = Promise.defer();
let resolvedA = false; let resolvedA = false;
scheduler.setProcessFunction(function(event) { scheduler.setProcessFunction(function(event) {
if (resolvedA) { if (resolvedA) {
@@ -80,7 +80,7 @@ describe("MatrixScheduler", function() {
it("should invoke the retryFn on failure and wait the amount of time specified", it("should invoke the retryFn on failure and wait the amount of time specified",
function(done) { function(done) {
const waitTimeMs = 1500; const waitTimeMs = 1500;
const retryDefer = q.defer(); const retryDefer = Promise.defer();
retryFn = function() { retryFn = function() {
retryDefer.resolve(); retryDefer.resolve();
return waitTimeMs; return waitTimeMs;
@@ -97,7 +97,7 @@ describe("MatrixScheduler", function() {
return defer.promise; return defer.promise;
} else if (procCount === 2) { } else if (procCount === 2) {
// don't care about this defer // don't care about this defer
return q.defer().promise; return Promise.defer().promise;
} }
expect(procCount).toBeLessThan(3); expect(procCount).toBeLessThan(3);
}); });
@@ -125,8 +125,8 @@ describe("MatrixScheduler", function() {
return "yep"; return "yep";
}; };
const deferA = q.defer(); const deferA = Promise.defer();
const deferB = q.defer(); const deferB = Promise.defer();
let procCount = 0; let procCount = 0;
scheduler.setProcessFunction(function(ev) { scheduler.setProcessFunction(function(ev) {
procCount += 1; procCount += 1;
@@ -177,7 +177,7 @@ describe("MatrixScheduler", function() {
const expectOrder = [ const expectOrder = [
eventA.getId(), eventB.getId(), eventD.getId(), eventA.getId(), eventB.getId(), eventD.getId(),
]; ];
const deferA = q.defer(); const deferA = Promise.defer();
scheduler.setProcessFunction(function(event) { scheduler.setProcessFunction(function(event) {
const id = expectOrder.shift(); const id = expectOrder.shift();
expect(id).toEqual(event.getId()); expect(id).toEqual(event.getId());

View File

@@ -1,6 +1,6 @@
"use strict"; "use strict";
import 'source-map-support/register'; import 'source-map-support/register';
const q = require("q"); import Promise from 'bluebird';
const sdk = require("../.."); const sdk = require("../..");
const EventTimeline = sdk.EventTimeline; const EventTimeline = sdk.EventTimeline;
const TimelineWindow = sdk.TimelineWindow; const TimelineWindow = sdk.TimelineWindow;
@@ -157,7 +157,7 @@ describe("TimelineWindow", function() {
client = {}; client = {};
client.getEventTimeline = function(timelineSet0, eventId0) { client.getEventTimeline = function(timelineSet0, eventId0) {
expect(timelineSet0).toBe(timelineSet); expect(timelineSet0).toBe(timelineSet);
return q(timeline); return Promise.resolve(timeline);
}; };
return new TimelineWindow(client, timelineSet, opts); return new TimelineWindow(client, timelineSet, opts);
@@ -191,7 +191,7 @@ describe("TimelineWindow", function() {
client.getEventTimeline = function(timelineSet0, eventId0) { client.getEventTimeline = function(timelineSet0, eventId0) {
expect(timelineSet0).toBe(timelineSet); expect(timelineSet0).toBe(timelineSet);
expect(eventId0).toEqual(eventId); expect(eventId0).toEqual(eventId);
return q(timeline); return Promise.resolve(timeline);
}; };
const timelineWindow = new TimelineWindow(client, timelineSet); const timelineWindow = new TimelineWindow(client, timelineSet);
@@ -219,7 +219,7 @@ describe("TimelineWindow", function() {
.toBe(false); .toBe(false);
expect(timelineWindow.canPaginate(EventTimeline.FORWARDS)) expect(timelineWindow.canPaginate(EventTimeline.FORWARDS))
.toBe(false); .toBe(false);
return q(timeline); return Promise.resolve(timeline);
}; };
timelineWindow.load(eventId, 3).then(function() { timelineWindow.load(eventId, 3).then(function() {
@@ -383,7 +383,7 @@ describe("TimelineWindow", function() {
expect(opts.limit).toEqual(2); expect(opts.limit).toEqual(2);
addEventsToTimeline(timeline, 3, false); addEventsToTimeline(timeline, 3, false);
return q(true); return Promise.resolve(true);
}; };
timelineWindow.load(eventId, 3).then(function() { timelineWindow.load(eventId, 3).then(function() {
@@ -416,7 +416,7 @@ describe("TimelineWindow", function() {
expect(opts.limit).toEqual(2); expect(opts.limit).toEqual(2);
addEventsToTimeline(timeline, 3, true); addEventsToTimeline(timeline, 3, true);
return q(true); return Promise.resolve(true);
}; };
timelineWindow.load(eventId, 3).then(function() { timelineWindow.load(eventId, 3).then(function() {
@@ -449,7 +449,7 @@ describe("TimelineWindow", function() {
expect(opts.backwards).toBe(false); expect(opts.backwards).toBe(false);
expect(opts.limit).toEqual(2); expect(opts.limit).toEqual(2);
paginateCount += 1; paginateCount += 1;
return q(true); return Promise.resolve(true);
}; };
timelineWindow.load(eventId, 3).then(function() { timelineWindow.load(eventId, 3).then(function() {

View File

@@ -23,7 +23,7 @@ const PushProcessor = require('./pushprocessor');
* @module client * @module client
*/ */
const EventEmitter = require("events").EventEmitter; const EventEmitter = require("events").EventEmitter;
const q = require("q"); import Promise from 'bluebird';
const url = require('url'); const url = require('url');
const httpApi = require("./http-api"); const httpApi = require("./http-api");
@@ -198,7 +198,7 @@ MatrixClient.prototype.clearStores = function() {
if (this._cryptoStore) { if (this._cryptoStore) {
promises.push(this._cryptoStore.deleteAllData()); promises.push(this._cryptoStore.deleteAllData());
} }
return q.all(promises); return Promise.all(promises);
}; };
/** /**
@@ -368,7 +368,7 @@ MatrixClient.prototype.uploadKeys = function() {
*/ */
MatrixClient.prototype.downloadKeys = function(userIds, forceDownload) { MatrixClient.prototype.downloadKeys = function(userIds, forceDownload) {
if (this._crypto === null) { if (this._crypto === null) {
return q.reject(new Error("End-to-end encryption disabled")); return Promise.reject(new Error("End-to-end encryption disabled"));
} }
return this._crypto.downloadKeys(userIds, forceDownload); return this._crypto.downloadKeys(userIds, forceDownload);
}; };
@@ -551,7 +551,7 @@ MatrixClient.prototype.setRoomEncryption = function(roomId, config) {
throw new Error("End-to-End encryption disabled"); throw new Error("End-to-End encryption disabled");
} }
this._crypto.setRoomEncryption(roomId, config); this._crypto.setRoomEncryption(roomId, config);
return q(); return Promise.resolve();
}; };
/** /**
@@ -577,7 +577,7 @@ MatrixClient.prototype.isRoomEncrypted = function(roomId) {
*/ */
MatrixClient.prototype.exportRoomKeys = function() { MatrixClient.prototype.exportRoomKeys = function() {
if (!this._crypto) { if (!this._crypto) {
return q.reject(new Error("End-to-end encryption disabled")); return Promise.reject(new Error("End-to-end encryption disabled"));
} }
return this._crypto.exportRoomKeys(); return this._crypto.exportRoomKeys();
}; };
@@ -730,10 +730,10 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
const room = this.getRoom(roomIdOrAlias); const room = this.getRoom(roomIdOrAlias);
if (room && room.hasMembershipState(this.credentials.userId, "join")) { if (room && room.hasMembershipState(this.credentials.userId, "join")) {
return q(room); return Promise.resolve(room);
} }
let sign_promise = q(); let sign_promise = Promise.resolve();
if (opts.inviteSignUrl) { if (opts.inviteSignUrl) {
sign_promise = this._http.requestOtherUrl( sign_promise = this._http.requestOtherUrl(
@@ -742,7 +742,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
); );
} }
const defer = q.defer(); const defer = Promise.defer();
const self = this; const self = this;
sign_promise.then(function(signed_invite_object) { sign_promise.then(function(signed_invite_object) {
@@ -761,7 +761,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
// v2 will do this for us // v2 will do this for us
// return syncApi.syncRoom(room); // return syncApi.syncRoom(room);
} }
return q(room); return Promise.resolve(room);
}).done(function(room) { }).done(function(room) {
_resolve(callback, defer, room); _resolve(callback, defer, room);
}, function(err) { }, function(err) {
@@ -981,10 +981,10 @@ MatrixClient.prototype.sendEvent = function(roomId, eventType, content, txnId,
// marks the event as sent/unsent // marks the event as sent/unsent
// returns a promise which resolves with the result of the send request // returns a promise which resolves with the result of the send request
function _sendEvent(client, room, event, callback) { function _sendEvent(client, room, event, callback) {
// Add an extra q() to turn synchronous exceptions into promise rejections, // Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections,
// so that we can handle synchronous and asynchronous exceptions with the // so that we can handle synchronous and asynchronous exceptions with the
// same code path. // same code path.
return q().then(function() { return Promise.resolve().then(function() {
let encryptionPromise = null; let encryptionPromise = null;
if (client._crypto) { if (client._crypto) {
encryptionPromise = client._crypto.encryptEventIfNeeded(event, room); encryptionPromise = client._crypto.encryptEventIfNeeded(event, room);
@@ -1238,7 +1238,7 @@ MatrixClient.prototype.sendHtmlEmote = function(roomId, body, htmlBody, callback
*/ */
MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) { MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) {
if (this.isGuest()) { if (this.isGuest()) {
return q({}); // guests cannot send receipts so don't bother. return Promise.resolve({}); // guests cannot send receipts so don't bother.
} }
const path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", { const path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", {
@@ -1315,7 +1315,7 @@ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
const key = ts + "_" + url; const key = ts + "_" + url;
const og = this.urlPreviewCache[key]; const og = this.urlPreviewCache[key];
if (og) { if (og) {
return q(og); return Promise.resolve(og);
} }
const self = this; const self = this;
@@ -1341,7 +1341,7 @@ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
*/ */
MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callback) { MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callback) {
if (this.isGuest()) { if (this.isGuest()) {
return q({}); // guests cannot send typing notifications so don't bother. return Promise.resolve({}); // guests cannot send typing notifications so don't bother.
} }
const path = utils.encodeUri("/rooms/$roomId/typing/$userId", { const path = utils.encodeUri("/rooms/$roomId/typing/$userId", {
@@ -1402,7 +1402,7 @@ MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, call
let identityServerUrl = this.getIdentityServerUrl(); let identityServerUrl = this.getIdentityServerUrl();
if (!identityServerUrl) { if (!identityServerUrl) {
return q.reject(new MatrixError({ return Promise.reject(new MatrixError({
error: "No supplied identity server URL", error: "No supplied identity server URL",
errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM", errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM",
})); }));
@@ -1742,13 +1742,13 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
} }
if (room.oldState.paginationToken === null) { if (room.oldState.paginationToken === null) {
return q(room); // already at the start. return Promise.resolve(room); // already at the start.
} }
// attempt to grab more events from the store first // attempt to grab more events from the store first
const numAdded = this.store.scrollback(room, limit).length; const numAdded = this.store.scrollback(room, limit).length;
if (numAdded === limit) { if (numAdded === limit) {
// store contained everything we needed. // store contained everything we needed.
return q(room); return Promise.resolve(room);
} }
// reduce the required number of events appropriately // reduce the required number of events appropriately
limit = limit - numAdded; limit = limit - numAdded;
@@ -1761,7 +1761,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
limit: limit, limit: limit,
dir: 'b', dir: 'b',
}; };
const defer = q.defer(); const defer = Promise.defer();
info = { info = {
promise: defer.promise, promise: defer.promise,
errorTs: null, errorTs: null,
@@ -1769,7 +1769,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
const self = this; const self = this;
// wait for a time before doing this request // wait for a time before doing this request
// (which may be 0 in order not to special case the code paths) // (which may be 0 in order not to special case the code paths)
q.delay(timeToWaitMs).then(function() { Promise.delay(timeToWaitMs).then(function() {
return self._http.authedRequest(callback, "GET", path, params); return self._http.authedRequest(callback, "GET", path, params);
}).done(function(res) { }).done(function(res) {
const matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self)); const matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self));
@@ -1812,7 +1812,7 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
const token = eventContext.getPaginateToken(backwards); const token = eventContext.getPaginateToken(backwards);
if (!token) { if (!token) {
// no more results. // no more results.
return q.reject(new Error("No paginate token")); return Promise.reject(new Error("No paginate token"));
} }
const dir = backwards ? 'b' : 'f'; const dir = backwards ? 'b' : 'f';
@@ -1881,7 +1881,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
} }
if (timelineSet.getTimelineForEvent(eventId)) { if (timelineSet.getTimelineForEvent(eventId)) {
return q(timelineSet.getTimelineForEvent(eventId)); return Promise.resolve(timelineSet.getTimelineForEvent(eventId));
} }
const path = utils.encodeUri( const path = utils.encodeUri(
@@ -1969,7 +1969,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
const token = eventTimeline.getPaginationToken(dir); const token = eventTimeline.getPaginationToken(dir);
if (!token) { if (!token) {
// no token - no results. // no token - no results.
return q(false); return Promise.resolve(false);
} }
const pendingRequest = eventTimeline._paginationRequests[dir]; const pendingRequest = eventTimeline._paginationRequests[dir];
@@ -2146,14 +2146,14 @@ MatrixClient.prototype.setGuestAccess = function(roomId, opts) {
guest_access: opts.allowJoin ? "can_join" : "forbidden", guest_access: opts.allowJoin ? "can_join" : "forbidden",
}); });
let readPromise = q(); let readPromise = Promise.resolve();
if (opts.allowRead) { if (opts.allowRead) {
readPromise = this.sendStateEvent(roomId, "m.room.history_visibility", { readPromise = this.sendStateEvent(roomId, "m.room.history_visibility", {
history_visibility: "world_readable", history_visibility: "world_readable",
}); });
} }
return q.all([readPromise, writePromise]); return Promise.all([readPromise, writePromise]);
}; };
// Registration/Login operations // Registration/Login operations
@@ -2421,7 +2421,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
} else if (!hasDontNotifyRule) { } else if (!hasDontNotifyRule) {
// Remove the existing one before setting the mute push rule // Remove the existing one before setting the mute push rule
// This is a workaround to SYN-590 (Push rule update fails) // This is a workaround to SYN-590 (Push rule update fails)
deferred = q.defer(); deferred = Promise.defer();
this.deletePushRule(scope, "room", roomPushRule.rule_id) this.deletePushRule(scope, "room", roomPushRule.rule_id)
.done(function() { .done(function() {
self.addPushRule(scope, "room", roomId, { self.addPushRule(scope, "room", roomId, {
@@ -2441,7 +2441,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
if (deferred) { if (deferred) {
// Update this.pushRules when the operation completes // Update this.pushRules when the operation completes
const ruleRefreshDeferred = q.defer(); const ruleRefreshDeferred = Promise.defer();
deferred.done(function() { deferred.done(function() {
self.getPushRules().done(function(result) { self.getPushRules().done(function(result) {
self.pushRules = result; self.pushRules = result;
@@ -2555,7 +2555,7 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) {
// nicely with HTTP errors. // nicely with HTTP errors.
if (!searchResults.next_batch) { if (!searchResults.next_batch) {
return q.reject(new Error("Cannot backpaginate event search any further")); return Promise.reject(new Error("Cannot backpaginate event search any further"));
} }
if (searchResults.pendingRequest) { if (searchResults.pendingRequest) {
@@ -2624,7 +2624,7 @@ MatrixClient.prototype._processRoomEventsSearch = function(searchResults, respon
MatrixClient.prototype.syncLeftRooms = function() { MatrixClient.prototype.syncLeftRooms = function() {
// Guard against multiple calls whilst ongoing and multiple calls post success // Guard against multiple calls whilst ongoing and multiple calls post success
if (this._syncedLeftRooms) { if (this._syncedLeftRooms) {
return q([]); // don't call syncRooms again if it succeeded. return Promise.resolve([]); // don't call syncRooms again if it succeeded.
} }
if (this._syncLeftRoomsPromise) { if (this._syncLeftRoomsPromise) {
return this._syncLeftRoomsPromise; // return the ongoing request return this._syncLeftRoomsPromise; // return the ongoing request
@@ -2683,7 +2683,7 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
if (allowCached) { if (allowCached) {
const filter = this.store.getFilter(userId, filterId); const filter = this.store.getFilter(userId, filterId);
if (filter) { if (filter) {
return q(filter); return Promise.resolve(filter);
} }
} }
@@ -2712,7 +2712,7 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
*/ */
MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) { MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
const filterId = this.store.getFilterIdByName(filterName); const filterId = this.store.getFilterIdByName(filterName);
let promise = q(); let promise = Promise.resolve();
const self = this; const self = this;
if (filterId) { if (filterId) {
@@ -2727,7 +2727,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
// super, just use that. // super, just use that.
// debuglog("Using existing filter ID %s: %s", filterId, // debuglog("Using existing filter ID %s: %s", filterId,
// JSON.stringify(oldDef)); // JSON.stringify(oldDef));
return q(filterId); return Promise.resolve(filterId);
} }
// debuglog("Existing filter ID %s: %s; new filter: %s", // debuglog("Existing filter ID %s: %s; new filter: %s",
// filterId, JSON.stringify(oldDef), JSON.stringify(newDef)); // filterId, JSON.stringify(oldDef), JSON.stringify(newDef));

View File

@@ -21,7 +21,7 @@ limitations under the License.
* Manages the list of other users' devices * Manages the list of other users' devices
*/ */
import q from 'q'; import Promise from 'bluebird';
import DeviceInfo from './deviceinfo'; import DeviceInfo from './deviceinfo';
import olmlib from './olmlib'; import olmlib from './olmlib';
@@ -96,7 +96,7 @@ export default class DeviceList {
console.log("downloadKeys: already have all necessary keys"); console.log("downloadKeys: already have all necessary keys");
} }
return q.all(promises).then(() => { return Promise.all(promises).then(() => {
return this._getDevicesFromStore(userIds); return this._getDevicesFromStore(userIds);
}); });
} }
@@ -309,7 +309,7 @@ export default class DeviceList {
_doKeyDownload(users) { _doKeyDownload(users) {
if (users.length === 0) { if (users.length === 0) {
// nothing to do // nothing to do
return q(); return Promise.resolve();
} }
const prom = this._serialiser.updateDevicesForUsers( const prom = this._serialiser.updateDevicesForUsers(
@@ -416,7 +416,7 @@ class DeviceListUpdateSerialiser {
this._nextSyncToken = syncToken; this._nextSyncToken = syncToken;
if (!this._queuedQueryDeferred) { if (!this._queuedQueryDeferred) {
this._queuedQueryDeferred = q.defer(); this._queuedQueryDeferred = Promise.defer();
} }
if (this._downloadInProgress) { if (this._downloadInProgress) {
@@ -459,7 +459,7 @@ class DeviceListUpdateSerialiser {
// //
// of course we ought to do this in a web worker or similar, but // of course we ought to do this in a web worker or similar, but
// this serves as an easy solution for now. // this serves as an easy solution for now.
let prom = q(); let prom = Promise.resolve();
for (const userId of downloadUsers) { for (const userId of downloadUsers) {
prom = prom.delay(5).then(() => { prom = prom.delay(5).then(() => {
this._processQueryResponseForUser(userId, dk[userId]); this._processQueryResponseForUser(userId, dk[userId]);

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from 'q'; import Promise from 'bluebird';
import utils from '../utils'; import utils from '../utils';
@@ -251,7 +251,7 @@ export default class OutgoingRoomKeyRequestManager {
_sendOutgoingRoomKeyRequests() { _sendOutgoingRoomKeyRequests() {
if (!this._clientRunning) { if (!this._clientRunning) {
this._sendOutgoingRoomKeyRequestsTimer = null; this._sendOutgoingRoomKeyRequestsTimer = null;
return q(); return Promise.resolve();
} }
console.log("Looking for queued outgoing room key requests"); console.log("Looking for queued outgoing room key requests");

View File

@@ -21,7 +21,7 @@ limitations under the License.
* @module crypto/algorithms/megolm * @module crypto/algorithms/megolm
*/ */
const q = require("q"); import Promise from 'bluebird';
const utils = require("../../utils"); const utils = require("../../utils");
const olmlib = require("../olmlib"); const olmlib = require("../olmlib");
@@ -132,7 +132,7 @@ function MegolmEncryption(params) {
// are using, and which devices we have shared the keys with. It resolves // are using, and which devices we have shared the keys with. It resolves
// with an OutboundSessionInfo (or undefined, for the first message in the // with an OutboundSessionInfo (or undefined, for the first message in the
// room). // room).
this._setupPromise = q(); this._setupPromise = Promise.resolve();
// default rotation periods // default rotation periods
this._sessionRotationPeriodMsgs = 100; this._sessionRotationPeriodMsgs = 100;
@@ -348,7 +348,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
} }
if (!haveTargets) { if (!haveTargets) {
return q(); return Promise.resolve();
} }
// TODO: retries // TODO: retries

View File

@@ -20,7 +20,7 @@ limitations under the License.
* *
* @module crypto/algorithms/olm * @module crypto/algorithms/olm
*/ */
const q = require('q'); import Promise from 'bluebird';
const utils = require("../../utils"); const utils = require("../../utils");
const olmlib = require("../olmlib"); const olmlib = require("../olmlib");
@@ -60,7 +60,7 @@ OlmEncryption.prototype._ensureSession = function(roomMembers) {
if (this._sessionPrepared) { if (this._sessionPrepared) {
// prep already done // prep already done
return q(); return Promise.resolve();
} }
const self = this; const self = this;

View File

@@ -21,7 +21,7 @@ limitations under the License.
*/ */
const anotherjson = require('another-json'); const anotherjson = require('another-json');
const q = require("q"); import Promise from 'bluebird';
import {EventEmitter} from 'events'; import {EventEmitter} from 'events';
const utils = require("../utils"); const utils = require("../utils");
@@ -287,7 +287,7 @@ function _maybeUploadOneTimeKeys(crypto) {
} }
crypto._oneTimeKeyCheckInProgress = true; crypto._oneTimeKeyCheckInProgress = true;
q().then(() => { Promise.resolve().then(() => {
// ask the server how many keys we have // ask the server how many keys we have
return crypto._baseApis.uploadKeysRequest({}, { return crypto._baseApis.uploadKeysRequest({}, {
device_id: crypto._deviceId, device_id: crypto._deviceId,
@@ -701,7 +701,7 @@ Crypto.prototype.isRoomEncrypted = function(roomId) {
* session export objects * session export objects
*/ */
Crypto.prototype.exportRoomKeys = function() { Crypto.prototype.exportRoomKeys = function() {
return q( return Promise.resolve(
this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map( this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map(
(s) => { (s) => {
const sess = this._olmDevice.exportInboundGroupSession( const sess = this._olmDevice.exportInboundGroupSession(

View File

@@ -20,7 +20,7 @@ limitations under the License.
* Utilities common to olm encryption algorithms * Utilities common to olm encryption algorithms
*/ */
const q = require('q'); import Promise from 'bluebird';
const anotherjson = require('another-json'); const anotherjson = require('another-json');
const utils = require("../utils"); const utils = require("../utils");
@@ -148,7 +148,7 @@ module.exports.ensureOlmSessionsForDevices = function(
} }
if (devicesWithoutSession.length === 0) { if (devicesWithoutSession.length === 0) {
return q(result); return Promise.resolve(result);
} }
// TODO: this has a race condition - if we try to send another message // TODO: this has a race condition - if we try to send another message

View File

@@ -1,4 +1,4 @@
import q from 'q'; import Promise from 'bluebird';
import utils from '../../utils'; import utils from '../../utils';
export const VERSION = 1; export const VERSION = 1;
@@ -39,7 +39,7 @@ export class Backend {
getOrAddOutgoingRoomKeyRequest(request) { getOrAddOutgoingRoomKeyRequest(request) {
const requestBody = request.requestBody; const requestBody = request.requestBody;
const deferred = q.defer(); const deferred = Promise.defer();
const txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite"); const txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite");
txn.onerror = deferred.reject; txn.onerror = deferred.reject;
@@ -81,7 +81,7 @@ export class Backend {
* not found * not found
*/ */
getOutgoingRoomKeyRequest(requestBody) { getOutgoingRoomKeyRequest(requestBody) {
const deferred = q.defer(); const deferred = Promise.defer();
const txn = this._db.transaction("outgoingRoomKeyRequests", "readonly"); const txn = this._db.transaction("outgoingRoomKeyRequests", "readonly");
txn.onerror = deferred.reject; txn.onerror = deferred.reject;
@@ -146,7 +146,7 @@ export class Backend {
*/ */
getOutgoingRoomKeyRequestByState(wantedStates) { getOutgoingRoomKeyRequestByState(wantedStates) {
if (wantedStates.length === 0) { if (wantedStates.length === 0) {
return q(null); return Promise.resolve(null);
} }
// this is a bit tortuous because we need to make sure we do the lookup // this is a bit tortuous because we need to make sure we do the lookup
@@ -284,7 +284,7 @@ function createDatabase(db) {
} }
function promiseifyTxn(txn) { function promiseifyTxn(txn) {
return new q.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
txn.oncomplete = resolve; txn.oncomplete = resolve;
txn.onerror = reject; txn.onerror = reject;
}); });

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from 'q'; import Promise from 'bluebird';
import MemoryCryptoStore from './memory-crypto-store'; import MemoryCryptoStore from './memory-crypto-store';
import * as IndexedDBCryptoStoreBackend from './indexeddb-crypto-store-backend'; import * as IndexedDBCryptoStoreBackend from './indexeddb-crypto-store-backend';
@@ -56,7 +56,7 @@ export default class IndexedDBCryptoStore {
return this._backendPromise; return this._backendPromise;
} }
this._backendPromise = new q.Promise((resolve, reject) => { this._backendPromise = new Promise((resolve, reject) => {
if (!this._indexedDB) { if (!this._indexedDB) {
reject(new Error('no indexeddb support available')); reject(new Error('no indexeddb support available'));
return; return;
@@ -107,7 +107,7 @@ export default class IndexedDBCryptoStore {
* @returns {Promise} resolves when the store has been cleared. * @returns {Promise} resolves when the store has been cleared.
*/ */
deleteAllData() { deleteAllData() {
return new q.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!this._indexedDB) { if (!this._indexedDB) {
reject(new Error('no indexeddb support available')); reject(new Error('no indexeddb support available'));
return; return;

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from 'q'; import Promise from 'bluebird';
import utils from '../../utils'; import utils from '../../utils';
@@ -38,7 +38,7 @@ export default class MemoryCryptoStore {
* @returns {Promise} Promise which resolves when the store has been cleared. * @returns {Promise} Promise which resolves when the store has been cleared.
*/ */
deleteAllData() { deleteAllData() {
return q(); return Promise.resolve();
} }
/** /**
@@ -90,10 +90,10 @@ export default class MemoryCryptoStore {
getOutgoingRoomKeyRequest(requestBody) { getOutgoingRoomKeyRequest(requestBody) {
for (const existing of this._outgoingRoomKeyRequests) { for (const existing of this._outgoingRoomKeyRequests) {
if (utils.deepCompare(existing.requestBody, requestBody)) { if (utils.deepCompare(existing.requestBody, requestBody)) {
return q(existing); return Promise.resolve(existing);
} }
} }
return q(null); return Promise.resolve(null);
} }
/** /**
@@ -109,11 +109,11 @@ export default class MemoryCryptoStore {
for (const req of this._outgoingRoomKeyRequests) { for (const req of this._outgoingRoomKeyRequests) {
for (const state of wantedStates) { for (const state of wantedStates) {
if (req.state === state) { if (req.state === state) {
return q(req); return Promise.resolve(req);
} }
} }
} }
return q(null); return Promise.resolve(null);
} }
/** /**
@@ -139,13 +139,13 @@ export default class MemoryCryptoStore {
`Cannot update room key request from ${expectedState} ` + `Cannot update room key request from ${expectedState} ` +
`as it was already updated to ${req.state}`, `as it was already updated to ${req.state}`,
); );
return q(null); return Promise.resolve(null);
} }
Object.assign(req, updates); Object.assign(req, updates);
return q(req); return Promise.resolve(req);
} }
return q(null); return Promise.resolve(null);
} }
/** /**
@@ -170,13 +170,13 @@ export default class MemoryCryptoStore {
`Cannot delete room key request in state ${req.state} ` `Cannot delete room key request in state ${req.state} `
+ `(expected ${expectedState})`, + `(expected ${expectedState})`,
); );
return q(null); return Promise.resolve(null);
} }
this._outgoingRoomKeyRequests.splice(i, 1); this._outgoingRoomKeyRequests.splice(i, 1);
return q(req); return Promise.resolve(req);
} }
return q(null); return Promise.resolve(null);
} }
} }

View File

@@ -18,7 +18,7 @@ limitations under the License.
* This is an internal module. See {@link MatrixHttpApi} for the public class. * This is an internal module. See {@link MatrixHttpApi} for the public class.
* @module http-api * @module http-api
*/ */
const q = require("q"); import Promise from 'bluebird';
const parseContentType = require('content-type').parse; const parseContentType = require('content-type').parse;
const utils = require("./utils"); const utils = require("./utils");
@@ -219,7 +219,7 @@ module.exports.MatrixHttpApi.prototype = {
} }
if (global.XMLHttpRequest) { if (global.XMLHttpRequest) {
const defer = q.defer(); const defer = Promise.defer();
const xhr = new global.XMLHttpRequest(); const xhr = new global.XMLHttpRequest();
upload.xhr = xhr; upload.xhr = xhr;
const cb = requestCallback(defer, opts.callback, this.opts.onlyData); const cb = requestCallback(defer, opts.callback, this.opts.onlyData);
@@ -343,7 +343,7 @@ module.exports.MatrixHttpApi.prototype = {
opts.form = params; opts.form = params;
} }
const defer = q.defer(); const defer = Promise.defer();
this.opts.request( this.opts.request(
opts, opts,
requestCallback(defer, callback, this.opts.onlyData), requestCallback(defer, callback, this.opts.onlyData),
@@ -676,7 +676,7 @@ module.exports.MatrixHttpApi.prototype = {
} }
} }
const defer = q.defer(); const defer = Promise.defer();
let timeoutId; let timeoutId;
let timedOut = false; let timedOut = false;

View File

@@ -17,7 +17,7 @@ limitations under the License.
"use strict"; "use strict";
/** @module interactive-auth */ /** @module interactive-auth */
const q = require("q"); import Promise from 'bluebird';
const url = require("url"); const url = require("url");
const utils = require("./utils"); const utils = require("./utils");
@@ -115,11 +115,11 @@ InteractiveAuth.prototype = {
* no suitable authentication flow can be found * no suitable authentication flow can be found
*/ */
attemptAuth: function() { attemptAuth: function() {
this._completionDeferred = q.defer(); this._completionDeferred = Promise.defer();
// wrap in a promise so that if _startNextAuthStage // wrap in a promise so that if _startNextAuthStage
// throws, it rejects the promise in a consistent way // throws, it rejects the promise in a consistent way
return q().then(() => { return Promise.resolve().then(() => {
// if we have no flows, try a request (we'll have // if we have no flows, try a request (we'll have
// just a session ID in _data if resuming) // just a session ID in _data if resuming)
if (!this._data.flows) { if (!this._data.flows) {
@@ -258,12 +258,12 @@ InteractiveAuth.prototype = {
// hackery to make sure that synchronous exceptions end up in the catch // hackery to make sure that synchronous exceptions end up in the catch
// handler (without the additional event loop entailed by q.fcall or an // handler (without the additional event loop entailed by q.fcall or an
// extra q().then) // extra Promise.resolve().then)
let prom; let prom;
try { try {
prom = this._requestCallback(auth, background); prom = this._requestCallback(auth, background);
} catch (e) { } catch (e) {
prom = q.reject(e); prom = Promise.reject(e);
} }
prom = prom.then( prom = prom.then(

View File

@@ -20,7 +20,7 @@ limitations under the License.
* @module scheduler * @module scheduler
*/ */
const utils = require("./utils"); const utils = require("./utils");
const q = require("q"); import Promise from 'bluebird';
const DEBUG = false; // set true to enable console logging. const DEBUG = false; // set true to enable console logging.
@@ -118,7 +118,7 @@ MatrixScheduler.prototype.queueEvent = function(event) {
if (!this._queues[queueName]) { if (!this._queues[queueName]) {
this._queues[queueName] = []; this._queues[queueName] = [];
} }
const defer = q.defer(); const defer = Promise.defer();
this._queues[queueName].push({ this._queues[queueName].push({
event: event, event: event,
defer: defer, defer: defer,

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from "q"; import Promise from 'bluebird';
import SyncAccumulator from "../sync-accumulator"; import SyncAccumulator from "../sync-accumulator";
import utils from "../utils"; import utils from "../utils";
@@ -44,7 +44,7 @@ function createDatabase(db) {
*/ */
function selectQuery(store, keyRange, resultMapper) { function selectQuery(store, keyRange, resultMapper) {
const query = store.openCursor(keyRange); const query = store.openCursor(keyRange);
return q.Promise((resolve, reject) => { /*eslint new-cap: 0*/ return new Promise((resolve, reject) => {
const results = []; const results = [];
query.onerror = (event) => { query.onerror = (event) => {
reject(new Error("Query failed: " + event.target.errorCode)); reject(new Error("Query failed: " + event.target.errorCode));
@@ -63,7 +63,7 @@ function selectQuery(store, keyRange, resultMapper) {
} }
function promiseifyTxn(txn) { function promiseifyTxn(txn) {
return new q.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
txn.oncomplete = function(event) { txn.oncomplete = function(event) {
resolve(event); resolve(event);
}; };
@@ -74,7 +74,7 @@ function promiseifyTxn(txn) {
} }
function promiseifyRequest(req) { function promiseifyRequest(req) {
return new q.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
req.onsuccess = function(event) { req.onsuccess = function(event) {
resolve(event); resolve(event);
}; };
@@ -113,7 +113,7 @@ LocalIndexedDBStoreBackend.prototype = {
*/ */
connect: function() { connect: function() {
if (this.db) { if (this.db) {
return q(); return Promise.resolve();
} }
const req = this.indexedDB.open(this._dbName, VERSION); const req = this.indexedDB.open(this._dbName, VERSION);
req.onupgradeneeded = (ev) => { req.onupgradeneeded = (ev) => {
@@ -143,7 +143,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves on success * @return {Promise} Resolves on success
*/ */
_init: function() { _init: function() {
return q.all([ return Promise.all([
this._loadAccountData(), this._loadAccountData(),
this._loadSyncData(), this._loadSyncData(),
]).then(([accountData, syncData]) => { ]).then(([accountData, syncData]) => {
@@ -163,7 +163,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolved when the database is cleared. * @return {Promise} Resolved when the database is cleared.
*/ */
clearDatabase: function() { clearDatabase: function() {
return new q.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log(`Removing indexeddb instance: ${this._dbName}`); console.log(`Removing indexeddb instance: ${this._dbName}`);
const req = this.indexedDB.deleteDatabase(this._dbName); const req = this.indexedDB.deleteDatabase(this._dbName);
@@ -204,18 +204,18 @@ LocalIndexedDBStoreBackend.prototype = {
if (copy === undefined) copy = true; if (copy === undefined) copy = true;
const data = this._syncAccumulator.getJSON(); const data = this._syncAccumulator.getJSON();
if (!data.nextBatch) return q(null); if (!data.nextBatch) return Promise.resolve(null);
if (copy) { if (copy) {
// We must deep copy the stored data so that the /sync processing code doesn't // We must deep copy the stored data so that the /sync processing code doesn't
// corrupt the internal state of the sync accumulator (it adds non-clonable keys) // corrupt the internal state of the sync accumulator (it adds non-clonable keys)
return q(utils.deepCopy(data)); return Promise.resolve(utils.deepCopy(data));
} else { } else {
return q(data); return Promise.resolve(data);
} }
}, },
setSyncData: function(syncData) { setSyncData: function(syncData) {
return q().then(() => { return Promise.resolve().then(() => {
this._syncAccumulator.accumulate(syncData); this._syncAccumulator.accumulate(syncData);
}); });
}, },
@@ -223,7 +223,7 @@ LocalIndexedDBStoreBackend.prototype = {
syncToDatabase: function(userTuples) { syncToDatabase: function(userTuples) {
const syncData = this._syncAccumulator.getJSON(); const syncData = this._syncAccumulator.getJSON();
return q.all([ return Promise.all([
this._persistUserPresenceEvents(userTuples), this._persistUserPresenceEvents(userTuples),
this._persistAccountData(syncData.accountData), this._persistAccountData(syncData.accountData),
this._persistSyncData(syncData.nextBatch, syncData.roomsData), this._persistSyncData(syncData.nextBatch, syncData.roomsData),
@@ -238,7 +238,7 @@ LocalIndexedDBStoreBackend.prototype = {
*/ */
_persistSyncData: function(nextBatch, roomsData) { _persistSyncData: function(nextBatch, roomsData) {
console.log("Persisting sync data up to ", nextBatch); console.log("Persisting sync data up to ", nextBatch);
return q.try(() => { return Promise.try(() => {
const txn = this.db.transaction(["sync"], "readwrite"); const txn = this.db.transaction(["sync"], "readwrite");
const store = txn.objectStore("sync"); const store = txn.objectStore("sync");
store.put({ store.put({
@@ -257,7 +257,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves if the events were persisted. * @return {Promise} Resolves if the events were persisted.
*/ */
_persistAccountData: function(accountData) { _persistAccountData: function(accountData) {
return q.try(() => { return Promise.try(() => {
const txn = this.db.transaction(["accountData"], "readwrite"); const txn = this.db.transaction(["accountData"], "readwrite");
const store = txn.objectStore("accountData"); const store = txn.objectStore("accountData");
for (let i = 0; i < accountData.length; i++) { for (let i = 0; i < accountData.length; i++) {
@@ -276,7 +276,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves if the users were persisted. * @return {Promise} Resolves if the users were persisted.
*/ */
_persistUserPresenceEvents: function(tuples) { _persistUserPresenceEvents: function(tuples) {
return q.try(() => { return Promise.try(() => {
const txn = this.db.transaction(["users"], "readwrite"); const txn = this.db.transaction(["users"], "readwrite");
const store = txn.objectStore("users"); const store = txn.objectStore("users");
for (const tuple of tuples) { for (const tuple of tuples) {
@@ -296,7 +296,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object[]>} A list of presence events in their raw form. * @return {Promise<Object[]>} A list of presence events in their raw form.
*/ */
getUserPresenceEvents: function() { getUserPresenceEvents: function() {
return q.try(() => { return Promise.try(() => {
const txn = this.db.transaction(["users"], "readonly"); const txn = this.db.transaction(["users"], "readonly");
const store = txn.objectStore("users"); const store = txn.objectStore("users");
return selectQuery(store, undefined, (cursor) => { return selectQuery(store, undefined, (cursor) => {
@@ -310,7 +310,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object[]>} A list of raw global account events. * @return {Promise<Object[]>} A list of raw global account events.
*/ */
_loadAccountData: function() { _loadAccountData: function() {
return q.try(() => { return Promise.try(() => {
const txn = this.db.transaction(["accountData"], "readonly"); const txn = this.db.transaction(["accountData"], "readonly");
const store = txn.objectStore("accountData"); const store = txn.objectStore("accountData");
return selectQuery(store, undefined, (cursor) => { return selectQuery(store, undefined, (cursor) => {
@@ -324,7 +324,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object>} An object with "roomsData" and "nextBatch" keys. * @return {Promise<Object>} An object with "roomsData" and "nextBatch" keys.
*/ */
_loadSyncData: function() { _loadSyncData: function() {
return q.try(() => { return Promise.try(() => {
const txn = this.db.transaction(["sync"], "readonly"); const txn = this.db.transaction(["sync"], "readonly");
const store = txn.objectStore("sync"); const store = txn.objectStore("sync");
return selectQuery(store, undefined, (cursor) => { return selectQuery(store, undefined, (cursor) => {

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from "q"; import Promise from 'bluebird';
/** /**
* An IndexedDB store backend where the actual backend sits in a web * An IndexedDB store backend where the actual backend sits in a web
@@ -96,9 +96,9 @@ RemoteIndexedDBStoreBackend.prototype = {
_doCmd: function(cmd, args) { _doCmd: function(cmd, args) {
// wrap in a q so if the postMessage throws, // wrap in a q so if the postMessage throws,
// the promise automatically gets rejected // the promise automatically gets rejected
return q().then(() => { return Promise.resolve().then(() => {
const seq = this._nextSeq++; const seq = this._nextSeq++;
const def = q.defer(); const def = Promise.defer();
this._inFlight[seq] = def; this._inFlight[seq] = def;

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from "q"; import Promise from 'bluebird';
import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js"; import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js";
/** /**
@@ -61,7 +61,7 @@ class IndexedDBStoreWorker {
// because it's a web worker and there is no window). // because it's a web worker and there is no window).
indexedDB, msg.args[0], indexedDB, msg.args[0],
); );
prom = q(); prom = Promise.resolve();
break; break;
case 'connect': case 'connect':
prom = this.backend.connect(); prom = this.backend.connect();

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import q from "q"; import Promise from 'bluebird';
import {MatrixInMemoryStore} from "./memory"; import {MatrixInMemoryStore} from "./memory";
import utils from "../utils"; import utils from "../utils";
import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js"; import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js";
@@ -115,7 +115,7 @@ utils.inherits(IndexedDBStore, MatrixInMemoryStore);
*/ */
IndexedDBStore.prototype.startup = function() { IndexedDBStore.prototype.startup = function() {
if (this.startedUp) { if (this.startedUp) {
return q(); return Promise.resolve();
} }
return this.backend.connect().then(() => { return this.backend.connect().then(() => {
@@ -164,7 +164,7 @@ IndexedDBStore.prototype.save = function() {
if (now - this._syncTs > WRITE_DELAY_MS) { if (now - this._syncTs > WRITE_DELAY_MS) {
return this._reallySave(); return this._reallySave();
} }
return q(); return Promise.resolve();
}; };
IndexedDBStore.prototype._reallySave = function() { IndexedDBStore.prototype._reallySave = function() {

View File

@@ -21,7 +21,7 @@ limitations under the License.
*/ */
const utils = require("../utils"); const utils = require("../utils");
const User = require("../models/user"); const User = require("../models/user");
const q = require("q"); import Promise from 'bluebird';
/** /**
* Construct a new in-memory data store for the Matrix Client. * Construct a new in-memory data store for the Matrix Client.
@@ -284,7 +284,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* @return {Promise} An immediately resolved promise. * @return {Promise} An immediately resolved promise.
*/ */
setSyncData: function(syncData) { setSyncData: function(syncData) {
return q(); return Promise.resolve();
}, },
/** /**
@@ -297,7 +297,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* @return {Promise} An immediately resolved promise. * @return {Promise} An immediately resolved promise.
*/ */
startup: function() { startup: function() {
return q(); return Promise.resolve();
}, },
/** /**
@@ -306,7 +306,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* is no saved sync data. * is no saved sync data.
*/ */
getSavedSync: function() { getSavedSync: function() {
return q(null); return Promise.resolve(null);
}, },
/** /**
@@ -329,6 +329,6 @@ module.exports.MatrixInMemoryStore.prototype = {
this.accountData = { this.accountData = {
// type : content // type : content
}; };
return q(); return Promise.resolve();
}, },
}; };

View File

@@ -15,7 +15,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
"use strict"; "use strict";
import q from "q"; import Promise from 'bluebird';
/** /**
* This is an internal module. * This is an internal module.
* @module store/stub * @module store/stub
@@ -189,7 +189,7 @@ StubStore.prototype = {
* @return {Promise} An immediately resolved promise. * @return {Promise} An immediately resolved promise.
*/ */
setSyncData: function(syncData) { setSyncData: function(syncData) {
return q(); return Promise.resolve();
}, },
/** /**
@@ -202,7 +202,7 @@ StubStore.prototype = {
* @return {Promise} An immediately resolved promise. * @return {Promise} An immediately resolved promise.
*/ */
startup: function() { startup: function() {
return q(); return Promise.resolve();
}, },
/** /**
@@ -211,7 +211,7 @@ StubStore.prototype = {
* is no saved sync data. * is no saved sync data.
*/ */
getSavedSync: function() { getSavedSync: function() {
return q(null); return Promise.resolve(null);
}, },
/** /**
@@ -220,7 +220,7 @@ StubStore.prototype = {
* @return {Promise} An immediately resolved promise. * @return {Promise} An immediately resolved promise.
*/ */
deleteAllData: function() { deleteAllData: function() {
return q(); return Promise.resolve();
}, },
}; };

View File

@@ -24,7 +24,7 @@ limitations under the License.
* an alternative syncing API, we may want to have a proper syncing interface * an alternative syncing API, we may want to have a proper syncing interface
* for HTTP and WS at some point. * for HTTP and WS at some point.
*/ */
const q = require("q"); import Promise from 'bluebird';
const User = require("./models/user"); const User = require("./models/user");
const Room = require("./models/room"); const Room = require("./models/room");
const utils = require("./utils"); const utils = require("./utils");
@@ -558,7 +558,7 @@ SyncApi.prototype._sync = function(syncOptions) {
// if there is data there. // if there is data there.
syncPromise = client.store.getSavedSync(); syncPromise = client.store.getSavedSync();
} else { } else {
syncPromise = q(null); syncPromise = Promise.resolve(null);
} }
syncPromise.then((savedSync) => { syncPromise.then((savedSync) => {
@@ -600,7 +600,7 @@ SyncApi.prototype._sync = function(syncOptions) {
return data; return data;
}); });
} else { } else {
return q(data); return Promise.resolve(data);
} }
}).done((data) => { }).done((data) => {
try { try {
@@ -1009,7 +1009,7 @@ SyncApi.prototype._startKeepAlives = function(delay) {
self._pokeKeepAlive(); self._pokeKeepAlive();
} }
if (!this._connectionReturnedDefer) { if (!this._connectionReturnedDefer) {
this._connectionReturnedDefer = q.defer(); this._connectionReturnedDefer = Promise.defer();
} }
return this._connectionReturnedDefer.promise; return this._connectionReturnedDefer.promise;
}; };
@@ -1127,7 +1127,7 @@ SyncApi.prototype._resolveInvites = function(room) {
const user = client.getUser(member.userId); const user = client.getUser(member.userId);
let promise; let promise;
if (user) { if (user) {
promise = q({ promise = Promise.resolve({
avatar_url: user.avatarUrl, avatar_url: user.avatarUrl,
displayname: user.displayName, displayname: user.displayName,
}); });

View File

@@ -17,7 +17,7 @@ limitations under the License.
/** @module timeline-window */ /** @module timeline-window */
const q = require("q"); import Promise from 'bluebird';
const EventTimeline = require("./models/event-timeline"); const EventTimeline = require("./models/event-timeline");
/** /**
@@ -133,17 +133,16 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) {
if (initialEventId) { if (initialEventId) {
const prom = this._client.getEventTimeline(this._timelineSet, initialEventId); const prom = this._client.getEventTimeline(this._timelineSet, initialEventId);
const promState = prom.inspect(); if (prom.isFulfilled()) {
if (promState.state == 'fulfilled') { initFields(prom.value());
initFields(promState.value); return Promise.resolve();
return q();
} else { } else {
return prom.then(initFields); return prom.then(initFields);
} }
} else { } else {
const tl = this._timelineSet.getLiveTimeline(); const tl = this._timelineSet.getLiveTimeline();
initFields(tl); initFields(tl);
return q(); return Promise.resolve();
} }
}; };
@@ -235,7 +234,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
if (!tl) { if (!tl) {
debuglog("TimelineWindow: no timeline yet"); debuglog("TimelineWindow: no timeline yet");
return q(false); return Promise.resolve(false);
} }
if (tl.pendingPaginate) { if (tl.pendingPaginate) {
@@ -255,20 +254,20 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
if (excess > 0) { if (excess > 0) {
this.unpaginate(excess, direction != EventTimeline.BACKWARDS); this.unpaginate(excess, direction != EventTimeline.BACKWARDS);
} }
return q(true); return Promise.resolve(true);
} }
if (!makeRequest || requestLimit === 0) { if (!makeRequest || requestLimit === 0) {
// todo: should we return something different to indicate that there // todo: should we return something different to indicate that there
// might be more events out there, but we haven't found them yet? // might be more events out there, but we haven't found them yet?
return q(false); return Promise.resolve(false);
} }
// try making a pagination request // try making a pagination request
const token = tl.timeline.getPaginationToken(direction); const token = tl.timeline.getPaginationToken(direction);
if (!token) { if (!token) {
debuglog("TimelineWindow: no token"); debuglog("TimelineWindow: no token");
return q(false); return Promise.resolve(false);
} }
debuglog("TimelineWindow: starting request"); debuglog("TimelineWindow: starting request");