@@ -6,11 +6,16 @@ import {
6
6
import Ajax from "./ajax"
7
7
8
8
let arrayBufferToBase64 = ( buffer ) => {
9
- let binary = ""
10
- let bytes = new Uint8Array ( buffer )
11
- let len = bytes . byteLength
12
- for ( let i = 0 ; i < len ; i ++ ) { binary += String . fromCharCode ( bytes [ i ] ) }
13
- return btoa ( binary )
9
+ return new Promise ( ( resolve , reject ) => {
10
+ let reader = new FileReader ( )
11
+ let blob = new Blob ( [ buffer ] )
12
+ reader . onload = e => {
13
+ let dataStart = reader . result . indexOf ( ',' )
14
+ resolve ( reader . result . slice ( dataStart + 1 ) )
15
+ }
16
+ reader . onerror = ( ) => reject ( )
17
+ reader . readAsDataURL ( blob )
18
+ } )
14
19
}
15
20
16
21
export default class LongPoll {
@@ -24,6 +29,7 @@ export default class LongPoll {
24
29
this . currentBatch = null
25
30
this . currentBatchTimer = null
26
31
this . batchBuffer = [ ]
32
+ this . sendResolver = Promise . resolve ( )
27
33
this . onopen = function ( ) { } // noop
28
34
this . onerror = function ( ) { } // noop
29
35
this . onmessage = function ( ) { } // noop
@@ -118,18 +124,26 @@ export default class LongPoll {
118
124
// pushes against an empty buffer
119
125
120
126
send ( body ) {
121
- if ( typeof ( body ) !== "string" ) { body = arrayBufferToBase64 ( body ) }
122
- if ( this . currentBatch ) {
123
- this . currentBatch . push ( body )
124
- } else if ( this . awaitingBatchAck ) {
125
- this . batchBuffer . push ( body )
126
- } else {
127
- this . currentBatch = [ body ]
128
- this . currentBatchTimer = setTimeout ( ( ) => {
129
- this . batchSend ( this . currentBatch )
130
- this . currentBatch = null
131
- } , 0 )
132
- }
127
+ this . sendResolver =
128
+ this . sendResolver
129
+ . then ( ( ) => {
130
+ if ( typeof ( body ) !== "string" ) { return arrayBufferToBase64 ( body ) }
131
+ return body
132
+ } )
133
+ . then ( body => {
134
+ if ( this . currentBatch ) {
135
+ this . currentBatch . push ( body )
136
+ } else if ( this . awaitingBatchAck ) {
137
+ this . batchBuffer . push ( body )
138
+ } else {
139
+ this . currentBatch = [ body ]
140
+ this . currentBatchTimer = setTimeout ( ( ) => {
141
+ this . batchSend ( this . currentBatch )
142
+ this . currentBatch = null
143
+ this . sendResolver = Promise . resolve ( )
144
+ } , 0 )
145
+ }
146
+ } )
133
147
}
134
148
135
149
batchSend ( messages ) {
0 commit comments