diff --git a/lib/shared/dm-ops/process-dm-ops.js b/lib/shared/dm-ops/process-dm-ops.js --- a/lib/shared/dm-ops/process-dm-ops.js +++ b/lib/shared/dm-ops/process-dm-ops.js @@ -311,18 +311,33 @@ const dispatchActionPromise = useDispatchActionPromise(); const { getDMOpsSendingPromise } = usePeerToPeerCommunication(); - return React.useCallback( - async (dmOperationSpecification: OutboundDMOperationSpecification) => { + const [operations, setOperations] = React.useState< + { + +operation: OutboundDMOperationSpecification, + +resolve: () => void, + }[], + >([]); + + React.useEffect(() => { + void (async () => { + if (operations.length === 0) { + return; + } + const [queueTop] = operations; + setOperations(oldOperations => { + const [, ...rest] = oldOperations; + return rest; + }); + const { operation, resolve } = queueTop; const { promise, dmOpID } = getDMOpsSendingPromise(); - await processDMOps(dmOperationSpecification, dmOpID); + await processDMOps(operation, dmOpID); if ( - dmOperationSpecification.type === - dmOperationSpecificationTypes.OUTBOUND && - !dmOpSpecs[dmOperationSpecification.op.type].supportsAutoRetry && - dmOperationSpecification.op.messageID + operation.type === dmOperationSpecificationTypes.OUTBOUND && + !dmOpSpecs[operation.op.type].supportsAutoRetry && + operation.op.messageID ) { - const messageID: string = dmOperationSpecification.op.messageID; + const messageID: string = operation.op.messageID; const sendingPromise: Promise = (async () => { const outboundP2PMessageIDs = await promise; @@ -332,7 +347,7 @@ }; })(); - void dispatchActionPromise( + await dispatchActionPromise( sendDMActionTypes, sendingPromise, undefined, @@ -341,8 +356,22 @@ }, ); } + resolve(); + })(); + }, [dispatchActionPromise, getDMOpsSendingPromise, operations, processDMOps]); + + return React.useCallback( + async (dmOperationSpecification: OutboundDMOperationSpecification) => { + const promise = new Promise(resolve => { + setOperations(oldOperations => [ + ...oldOperations, + { operation: dmOperationSpecification, resolve }, + ]); + }); + + return promise; }, - [dispatchActionPromise, getDMOpsSendingPromise, processDMOps], + [], ); }