q(...) -> Promise.resolve

```
find src test -name '*.js' | xargs perl -i -pe 's/\b[qQ]\(/Promise.resolve(/'
```
This commit is contained in:
Richard van der Hoff 2017-07-12 14:02:00 +01:00
parent a06bd84213
commit 0254d2b3a2
25 changed files with 57 additions and 57 deletions

View file

@ -116,12 +116,12 @@ export function loadSession(opts) {
*/ */
export function attemptTokenLogin(queryParams, defaultDeviceDisplayName) { export function attemptTokenLogin(queryParams, defaultDeviceDisplayName) {
if (!queryParams.loginToken) { if (!queryParams.loginToken) {
return q(false); return Promise.resolve(false);
} }
if (!queryParams.homeserver) { if (!queryParams.homeserver) {
console.warn("Cannot log in with token: can't determine HS URL to use"); console.warn("Cannot log in with token: can't determine HS URL to use");
return q(false); return Promise.resolve(false);
} }
// create a temporary MatrixClient to do the login // create a temporary MatrixClient to do the login
@ -197,7 +197,7 @@ function _registerAsGuest(hsUrl, isUrl, defaultDeviceDisplayName) {
// localStorage (e.g. teamToken, isGuest etc.) // localStorage (e.g. teamToken, isGuest etc.)
function _restoreFromLocalStorage() { function _restoreFromLocalStorage() {
if (!localStorage) { if (!localStorage) {
return q(false); return Promise.resolve(false);
} }
const hsUrl = localStorage.getItem("mx_hs_url"); const hsUrl = localStorage.getItem("mx_hs_url");
const isUrl = localStorage.getItem("mx_is_url") || 'https://matrix.org'; const isUrl = localStorage.getItem("mx_is_url") || 'https://matrix.org';
@ -229,7 +229,7 @@ function _restoreFromLocalStorage() {
} }
} else { } else {
console.log("No previous session found."); console.log("No previous session found.");
return q(false); return Promise.resolve(false);
} }
} }

View file

@ -144,7 +144,7 @@ export default class Login {
const client = this._createTemporaryClient(); const client = this._createTemporaryClient();
return client.login('m.login.password', loginParams).then(function(data) { return client.login('m.login.password', loginParams).then(function(data) {
return q({ return Promise.resolve({
homeserverUrl: self._hsUrl, homeserverUrl: self._hsUrl,
identityServerUrl: self._isUrl, identityServerUrl: self._isUrl,
userId: data.user_id, userId: data.user_id,
@ -160,7 +160,7 @@ export default class Login {
}); });
return fbClient.login('m.login.password', loginParams).then(function(data) { return fbClient.login('m.login.password', loginParams).then(function(data) {
return q({ return Promise.resolve({
homeserverUrl: self._fallbackHsUrl, homeserverUrl: self._fallbackHsUrl,
identityServerUrl: self._isUrl, identityServerUrl: self._isUrl,
userId: data.user_id, userId: data.user_id,

View file

@ -102,7 +102,7 @@ export function guessAndSetDMRoom(room, isDirect) {
*/ */
export function setDMRoom(roomId, userId) { export function setDMRoom(roomId, userId) {
if (MatrixClientPeg.get().isGuest()) { if (MatrixClientPeg.get().isGuest()) {
return q(); return Promise.resolve();
} }
const mDirectEvent = MatrixClientPeg.get().getAccountData('m.direct'); const mDirectEvent = MatrixClientPeg.get().getAccountData('m.direct');

View file

@ -39,7 +39,7 @@ class ScalarAuthClient {
// Returns a scalar_token string // Returns a scalar_token string
getScalarToken() { getScalarToken() {
var tok = window.localStorage.getItem("mx_scalar_token"); var tok = window.localStorage.getItem("mx_scalar_token");
if (tok) return q(tok); if (tok) return Promise.resolve(tok);
// No saved token, so do the dance to get one. First, we // No saved token, so do the dance to get one. First, we
// need an openid bearer token from the HS. // need an openid bearer token from the HS.

View file

@ -48,7 +48,7 @@ export default {
loadThreePids: function() { loadThreePids: function() {
if (MatrixClientPeg.get().isGuest()) { if (MatrixClientPeg.get().isGuest()) {
return q({ return Promise.resolve({
threepids: [], threepids: [],
}); // guests can't poke 3pid endpoint }); // guests can't poke 3pid endpoint
} }

View file

@ -57,7 +57,7 @@ export async function getCompletions(query: string, selection: SelectionRange, f
state (== "fulfilled" || "rejected") and value. */ state (== "fulfilled" || "rejected") and value. */
const completionsList = await Q.allSettled( const completionsList = await Q.allSettled(
PROVIDERS.map(provider => { PROVIDERS.map(provider => {
return Q(provider.getCompletions(query, selection, force)) return Promise.resolve(provider.getCompletions(query, selection, force))
.timeout(PROVIDER_COMPLETION_TIMEOUT); .timeout(PROVIDER_COMPLETION_TIMEOUT);
}), }),
); );

View file

@ -323,9 +323,9 @@ module.exports = React.createClass({
return; return;
} }
// the extra q() ensures that synchronous exceptions hit the same codepath as // the extra Promise.resolve() ensures that synchronous exceptions hit the same codepath as
// asynchronous ones. // asynchronous ones.
return q().then(() => { return Promise.resolve().then(() => {
return Lifecycle.loadSession({ return Lifecycle.loadSession({
fragmentQueryParams: this.props.startingFragmentQueryParams, fragmentQueryParams: this.props.startingFragmentQueryParams,
enableGuest: this.props.enableGuest, enableGuest: this.props.enableGuest,
@ -694,7 +694,7 @@ module.exports = React.createClass({
// Wait for the first sync to complete so that if a room does have an alias, // Wait for the first sync to complete so that if a room does have an alias,
// it would have been retrieved. // it would have been retrieved.
let waitFor = q(null); let waitFor = Promise.resolve(null);
if (!this.firstSyncComplete) { if (!this.firstSyncComplete) {
if (!this.firstSyncPromise) { if (!this.firstSyncPromise) {
console.warn('Cannot view a room before first sync. room_id:', roomInfo.room_id); console.warn('Cannot view a room before first sync. room_id:', roomInfo.room_id);

View file

@ -788,7 +788,7 @@ module.exports = React.createClass({
onSearchResultsFillRequest: function(backwards) { onSearchResultsFillRequest: function(backwards) {
if (!backwards) { if (!backwards) {
return q(false); return Promise.resolve(false);
} }
if (this.state.searchResults.next_batch) { if (this.state.searchResults.next_batch) {
@ -798,7 +798,7 @@ module.exports = React.createClass({
return this._handleSearchResult(searchPromise); return this._handleSearchResult(searchPromise);
} else { } else {
debuglog("no more search results"); debuglog("no more search results");
return q(false); return Promise.resolve(false);
} }
}, },
@ -859,7 +859,7 @@ module.exports = React.createClass({
return; return;
} }
q().then(() => { Promise.resolve().then(() => {
const signUrl = this.props.thirdPartyInvite ? const signUrl = this.props.thirdPartyInvite ?
this.props.thirdPartyInvite.inviteSignUrl : undefined; this.props.thirdPartyInvite.inviteSignUrl : undefined;
dis.dispatch({ dis.dispatch({
@ -878,7 +878,7 @@ module.exports = React.createClass({
} }
} }
} }
return q(); return Promise.resolve();
}); });
}, },

View file

@ -145,7 +145,7 @@ module.exports = React.createClass({
return { return {
stickyBottom: true, stickyBottom: true,
startAtBottom: true, startAtBottom: true,
onFillRequest: function(backwards) { return q(false); }, onFillRequest: function(backwards) { return Promise.resolve(false); },
onUnfillRequest: function(backwards, scrollToken) {}, onUnfillRequest: function(backwards, scrollToken) {},
onScroll: function() {}, onScroll: function() {},
}; };

View file

@ -311,13 +311,13 @@ var TimelinePanel = React.createClass({
if (!this.state[canPaginateKey]) { if (!this.state[canPaginateKey]) {
debuglog("TimelinePanel: have given up", dir, "paginating this timeline"); debuglog("TimelinePanel: have given up", dir, "paginating this timeline");
return q(false); return Promise.resolve(false);
} }
if(!this._timelineWindow.canPaginate(dir)) { if(!this._timelineWindow.canPaginate(dir)) {
debuglog("TimelinePanel: can't", dir, "paginate any further"); debuglog("TimelinePanel: can't", dir, "paginate any further");
this.setState({[canPaginateKey]: false}); this.setState({[canPaginateKey]: false});
return q(false); return Promise.resolve(false);
} }
debuglog("TimelinePanel: Initiating paginate; backwards:"+backwards); debuglog("TimelinePanel: Initiating paginate; backwards:"+backwards);

View file

@ -203,7 +203,7 @@ module.exports = React.createClass({
this._addThreepid = null; this._addThreepid = null;
if (PlatformPeg.get()) { if (PlatformPeg.get()) {
q().then(() => { Promise.resolve().then(() => {
return PlatformPeg.get().getAppVersion(); return PlatformPeg.get().getAppVersion();
}).done((appVersion) => { }).done((appVersion) => {
if (this._unmounted) return; if (this._unmounted) return;
@ -301,7 +301,7 @@ module.exports = React.createClass({
}, },
_refreshMediaDevices: function() { _refreshMediaDevices: function() {
q().then(() => { Promise.resolve().then(() => {
return CallMediaHandler.getDevices(); return CallMediaHandler.getDevices();
}).then((mediaDevices) => { }).then((mediaDevices) => {
// console.log("got mediaDevices", mediaDevices, this._unmounted); // console.log("got mediaDevices", mediaDevices, this._unmounted);

View file

@ -180,7 +180,7 @@ module.exports = React.createClass({
// will just nop. The point of this being we might not have the email address // will just nop. The point of this being we might not have the email address
// that the user registered with at this stage (depending on whether this // that the user registered with at this stage (depending on whether this
// is the client they initiated registration). // is the client they initiated registration).
let trackPromise = q(null); let trackPromise = Promise.resolve(null);
if (this._rtsClient && extra.emailSid) { if (this._rtsClient && extra.emailSid) {
// Track referral if this.props.referrer set, get team_token in order to // Track referral if this.props.referrer set, get team_token in order to
// retrieve team config and see welcome page etc. // retrieve team config and see welcome page etc.
@ -232,7 +232,7 @@ module.exports = React.createClass({
_setupPushers: function(matrixClient) { _setupPushers: function(matrixClient) {
if (!this.props.brand) { if (!this.props.brand) {
return q(); return Promise.resolve();
} }
return matrixClient.getPushers().then((resp)=>{ return matrixClient.getPushers().then((resp)=>{
const pushers = resp.pushers; const pushers = resp.pushers;

View file

@ -148,5 +148,5 @@ EditableTextContainer.defaultProps = {
initialValue: "", initialValue: "",
placeholder: "", placeholder: "",
blurToSubmit: false, blurToSubmit: false,
onSubmit: function(v) {return q(); }, onSubmit: function(v) {return Promise.resolve(); },
}; };

View file

@ -123,7 +123,7 @@ module.exports = React.createClass({
this.fixupHeight(); this.fixupHeight();
const content = this.props.mxEvent.getContent(); const content = this.props.mxEvent.getContent();
if (content.file !== undefined && this.state.decryptedUrl === null) { if (content.file !== undefined && this.state.decryptedUrl === null) {
let thumbnailPromise = q(null); let thumbnailPromise = Promise.resolve(null);
if (content.info.thumbnail_file) { if (content.info.thumbnail_file) {
thumbnailPromise = decryptFile( thumbnailPromise = decryptFile(
content.info.thumbnail_file, content.info.thumbnail_file,

View file

@ -89,7 +89,7 @@ module.exports = React.createClass({
componentDidMount: function() { componentDidMount: function() {
const content = this.props.mxEvent.getContent(); const content = this.props.mxEvent.getContent();
if (content.file !== undefined && this.state.decryptedUrl === null) { if (content.file !== undefined && this.state.decryptedUrl === null) {
var thumbnailPromise = q(null); var thumbnailPromise = Promise.resolve(null);
if (content.info.thumbnail_file) { if (content.info.thumbnail_file) {
thumbnailPromise = decryptFile( thumbnailPromise = decryptFile(
content.info.thumbnail_file content.info.thumbnail_file

View file

@ -72,7 +72,7 @@ module.exports = React.createClass({
saveSettings: function() { // : Promise saveSettings: function() { // : Promise
if (!this.state.hasChanged) { if (!this.state.hasChanged) {
return q(); // They didn't explicitly give a color to save. return Promise.resolve(); // They didn't explicitly give a color to save.
} }
var originalState = this.getInitialState(); var originalState = this.getInitialState();
if (originalState.primary_color !== this.state.primary_color || if (originalState.primary_color !== this.state.primary_color ||
@ -92,7 +92,7 @@ module.exports = React.createClass({
} }
}); });
} }
return q(); // no color diff return Promise.resolve(); // no color diff
}, },
_getColorIndex: function(scheme) { _getColorIndex: function(scheme) {

View file

@ -64,7 +64,7 @@ export default class Autocomplete extends React.Component {
// Hide the autocomplete box // Hide the autocomplete box
hide: true, hide: true,
}); });
return Q(null); return Promise.resolve(null);
} }
let autocompleteDelay = UserSettingsStore.getLocalSetting('autocompleteDelay', 200); let autocompleteDelay = UserSettingsStore.getLocalSetting('autocompleteDelay', 200);

View file

@ -305,25 +305,25 @@ module.exports = React.createClass({
}, },
saveAliases: function() { saveAliases: function() {
if (!this.refs.alias_settings) { return [q()]; } if (!this.refs.alias_settings) { return [Promise.resolve()]; }
return this.refs.alias_settings.saveSettings(); return this.refs.alias_settings.saveSettings();
}, },
saveColor: function() { saveColor: function() {
if (!this.refs.color_settings) { return q(); } if (!this.refs.color_settings) { return Promise.resolve(); }
return this.refs.color_settings.saveSettings(); return this.refs.color_settings.saveSettings();
}, },
saveUrlPreviewSettings: function() { saveUrlPreviewSettings: function() {
if (!this.refs.url_preview_settings) { return q(); } if (!this.refs.url_preview_settings) { return Promise.resolve(); }
return this.refs.url_preview_settings.saveSettings(); return this.refs.url_preview_settings.saveSettings();
}, },
saveEnableEncryption: function() { saveEnableEncryption: function() {
if (!this.refs.encrypt) { return q(); } if (!this.refs.encrypt) { return Promise.resolve(); }
var encrypt = this.refs.encrypt.checked; var encrypt = this.refs.encrypt.checked;
if (!encrypt) { return q(); } if (!encrypt) { return Promise.resolve(); }
var roomId = this.props.room.roomId; var roomId = this.props.room.roomId;
return MatrixClientPeg.get().sendStateEvent( return MatrixClientPeg.get().sendStateEvent(

View file

@ -42,7 +42,7 @@ function createRoom(opts) {
const client = MatrixClientPeg.get(); const client = MatrixClientPeg.get();
if (client.isGuest()) { if (client.isGuest()) {
dis.dispatch({action: 'view_set_mxid'}); dis.dispatch({action: 'view_set_mxid'});
return q(null); return Promise.resolve(null);
} }
const defaultPreset = opts.dmUserId ? 'trusted_private_chat' : 'private_chat'; const defaultPreset = opts.dmUserId ? 'trusted_private_chat' : 'private_chat';
@ -92,7 +92,7 @@ function createRoom(opts) {
if (opts.dmUserId) { if (opts.dmUserId) {
return Rooms.setDMRoom(roomId, opts.dmUserId); return Rooms.setDMRoom(roomId, opts.dmUserId);
} else { } else {
return q(); return Promise.resolve();
} }
}).then(function() { }).then(function() {
// NB createRoom doesn't block on the client seeing the echo that the // NB createRoom doesn't block on the client seeing the echo that the

View file

@ -53,7 +53,7 @@ export function readBlobAsDataUri(file) {
export function decryptFile(file) { export function decryptFile(file) {
const url = MatrixClientPeg.get().mxcUrlToHttp(file.url); const url = MatrixClientPeg.get().mxcUrlToHttp(file.url);
// Download the encrypted file as an array buffer. // Download the encrypted file as an array buffer.
return q(fetch(url)).then(function(response) { return Promise.resolve(fetch(url)).then(function(response) {
return response.arrayBuffer(); return response.arrayBuffer();
}).then(function(responseData) { }).then(function(responseData) {
// Decrypt the array buffer using the information taken from // Decrypt the array buffer using the information taken from

View file

@ -58,7 +58,7 @@ var Tester = React.createClass({
if (handler) { if (handler) {
res = handler(); res = handler();
} else { } else {
res = q(false); res = Promise.resolve(false);
} }
if (defer) { if (defer) {
@ -168,7 +168,7 @@ describe('ScrollPanel', function() {
const sp = tester.scrollPanel(); const sp = tester.scrollPanel();
let retriesRemaining = 1; let retriesRemaining = 1;
const awaitReady = function() { const awaitReady = function() {
return q().then(() => { return Promise.resolve().then(() => {
if (sp._pendingFillRequests.b === false && if (sp._pendingFillRequests.b === false &&
sp._pendingFillRequests.f === false sp._pendingFillRequests.f === false
) { ) {
@ -195,7 +195,7 @@ describe('ScrollPanel', function() {
it('should handle scrollEvent strangeness', function() { it('should handle scrollEvent strangeness', function() {
const events = []; const events = [];
return q().then(() => { return Promise.resolve().then(() => {
// initialise with a load of events // initialise with a load of events
for (let i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
events.push(i+80); events.push(i+80);
@ -227,7 +227,7 @@ describe('ScrollPanel', function() {
it('should not get stuck in #528 workaround', function(done) { it('should not get stuck in #528 workaround', function(done) {
var events = []; var events = [];
q().then(() => { Promise.resolve().then(() => {
// initialise with a bunch of events // initialise with a bunch of events
for (var i = 0; i < 40; i++) { for (var i = 0; i < 40; i++) {
events.push(i); events.push(i);

View file

@ -145,7 +145,7 @@ describe('TimelinePanel', function() {
// panel isn't paginating // panel isn't paginating
var awaitPaginationCompletion = function() { var awaitPaginationCompletion = function() {
if(!panel.state.forwardPaginating) if(!panel.state.forwardPaginating)
return q(); return Promise.resolve();
else else
return q.delay(0).then(awaitPaginationCompletion); return q.delay(0).then(awaitPaginationCompletion);
}; };
@ -214,7 +214,7 @@ describe('TimelinePanel', function() {
client.paginateEventTimeline = sinon.spy((tl, opts) => { client.paginateEventTimeline = sinon.spy((tl, opts) => {
console.log("paginate:", opts); console.log("paginate:", opts);
expect(opts.backwards).toBe(true); expect(opts.backwards).toBe(true);
return q(true); return Promise.resolve(true);
}); });
var rendered = ReactDOM.render( var rendered = ReactDOM.render(

View file

@ -50,7 +50,7 @@ describe('InteractiveAuthDialog', function () {
it('Should successfully complete a password flow', function() { it('Should successfully complete a password flow', function() {
const onFinished = sinon.spy(); const onFinished = sinon.spy();
const doRequest = sinon.stub().returns(q({a:1})); const doRequest = sinon.stub().returns(Promise.resolve({a:1}));
// tell the stub matrixclient to return a real userid // tell the stub matrixclient to return a real userid
var client = MatrixClientPeg.get(); var client = MatrixClientPeg.get();

View file

@ -39,7 +39,7 @@ describe('RoomViewStore', function() {
}); });
it('can be used to view a room by alias and join', function(done) { it('can be used to view a room by alias and join', function(done) {
peg.get().getRoomIdForAlias.returns(q({room_id: "!randomcharacters:aser.ver"})); peg.get().getRoomIdForAlias.returns(Promise.resolve({room_id: "!randomcharacters:aser.ver"}));
peg.get().joinRoom = (roomAddress) => { peg.get().joinRoom = (roomAddress) => {
expect(roomAddress).toBe("#somealias2:aser.ver"); expect(roomAddress).toBe("#somealias2:aser.ver");
done(); done();

View file

@ -75,12 +75,12 @@ export function createTestClient() {
on: sinon.stub(), on: sinon.stub(),
removeListener: sinon.stub(), removeListener: sinon.stub(),
isRoomEncrypted: sinon.stub().returns(false), isRoomEncrypted: sinon.stub().returns(false),
peekInRoom: sinon.stub().returns(q(mkStubRoom())), peekInRoom: sinon.stub().returns(Promise.resolve(mkStubRoom())),
paginateEventTimeline: sinon.stub().returns(q()), paginateEventTimeline: sinon.stub().returns(Promise.resolve()),
sendReadReceipt: sinon.stub().returns(q()), sendReadReceipt: sinon.stub().returns(Promise.resolve()),
getRoomIdForAlias: sinon.stub().returns(q()), getRoomIdForAlias: sinon.stub().returns(Promise.resolve()),
getProfileInfo: sinon.stub().returns(q({})), getProfileInfo: sinon.stub().returns(Promise.resolve({})),
getAccountData: (type) => { getAccountData: (type) => {
return mkEvent({ return mkEvent({
type, type,
@ -89,9 +89,9 @@ export function createTestClient() {
}); });
}, },
setAccountData: sinon.stub(), setAccountData: sinon.stub(),
sendTyping: sinon.stub().returns(q({})), sendTyping: sinon.stub().returns(Promise.resolve({})),
sendTextMessage: () => q({}), sendTextMessage: () => Promise.resolve({}),
sendHtmlMessage: () => q({}), sendHtmlMessage: () => Promise.resolve({}),
getSyncState: () => "SYNCING", getSyncState: () => "SYNCING",
generateClientSecret: () => "t35tcl1Ent5ECr3T", generateClientSecret: () => "t35tcl1Ent5ECr3T",
isGuest: () => false, isGuest: () => false,
@ -101,13 +101,13 @@ export function createTestClient() {
export function createTestRtsClient(teamMap, sidMap) { export function createTestRtsClient(teamMap, sidMap) {
return { return {
getTeamsConfig() { getTeamsConfig() {
return q(Object.keys(teamMap).map((token) => teamMap[token])); return Promise.resolve(Object.keys(teamMap).map((token) => teamMap[token]));
}, },
trackReferral(referrer, emailSid, clientSecret) { trackReferral(referrer, emailSid, clientSecret) {
return q({team_token: sidMap[emailSid]}); return Promise.resolve({team_token: sidMap[emailSid]});
}, },
getTeam(teamToken) { getTeam(teamToken) {
return q(teamMap[teamToken]); return Promise.resolve(teamMap[teamToken]);
}, },
}; };
} }