1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-11-26 17:03:12 +03:00

q(...) -> Promise.resolve

```
find src spec -name '*.js' |
    xargs perl -i -pe 's/\bq(\([^(]*\))/Promise.resolve$1/'
```
This commit is contained in:
Richard van der Hoff
2017-07-10 16:04:25 +01:00
parent b96062b6de
commit a5d3dd942e
24 changed files with 92 additions and 92 deletions

View File

@@ -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")

View File

@@ -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
@@ -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))
@@ -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))
@@ -622,7 +622,7 @@ describe("MatrixClient crypto", function() {
}); });
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

@@ -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',
}}}), }}}),
); );

View File

@@ -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

@@ -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 = (
@@ -117,7 +117,7 @@ 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 q.defer().promise;
@@ -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,

View File

@@ -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

@@ -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();
}; };
/** /**
@@ -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(
@@ -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", {
@@ -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;
@@ -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,7 +2146,7 @@ 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",
@@ -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

@@ -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(
@@ -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

@@ -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

@@ -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

@@ -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

@@ -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

@@ -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

@@ -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

View File

@@ -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

@@ -119,7 +119,7 @@ InteractiveAuth.prototype = {
// 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,7 +258,7 @@ 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);

View File

@@ -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) => {
@@ -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);
}); });
}, },

View File

@@ -96,7 +96,7 @@ 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 = q.defer();

View File

@@ -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

@@ -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

@@ -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

@@ -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

@@ -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 {
@@ -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

@@ -136,14 +136,14 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) {
const promState = prom.inspect(); const promState = prom.inspect();
if (promState.state == 'fulfilled') { if (promState.state == 'fulfilled') {
initFields(promState.value); initFields(promState.value);
return q(); return Promise.resolve();
} 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 +235,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 +255,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");