Skip to content

Commit a8f6638

Browse files
fix(scheduler): ensure jobs are in the correct order (#7748)
close #7576
1 parent 089d36d commit a8f6638

File tree

2 files changed

+60
-3
lines changed

2 files changed

+60
-3
lines changed

Diff for: packages/runtime-core/__tests__/scheduler.spec.ts

+53-1
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ describe('scheduler', () => {
143143
queueJob(job1)
144144
// cb2 should execute before the job
145145
queueJob(cb2)
146+
queueJob(cb3)
146147
}
147148
cb1.pre = true
148149

@@ -152,9 +153,60 @@ describe('scheduler', () => {
152153
cb2.pre = true
153154
cb2.id = 1
154155

156+
const cb3 = () => {
157+
calls.push('cb3')
158+
}
159+
cb3.pre = true
160+
cb3.id = 1
161+
155162
queueJob(cb1)
156163
await nextTick()
157-
expect(calls).toEqual(['cb1', 'cb2', 'job1'])
164+
expect(calls).toEqual(['cb1', 'cb2', 'cb3', 'job1'])
165+
})
166+
167+
it('should insert jobs after pre jobs with the same id', async () => {
168+
const calls: string[] = []
169+
const job1 = () => {
170+
calls.push('job1')
171+
}
172+
job1.id = 1
173+
job1.pre = true
174+
const job2 = () => {
175+
calls.push('job2')
176+
queueJob(job5)
177+
queueJob(job6)
178+
}
179+
job2.id = 2
180+
job2.pre = true
181+
const job3 = () => {
182+
calls.push('job3')
183+
}
184+
job3.id = 2
185+
job3.pre = true
186+
const job4 = () => {
187+
calls.push('job4')
188+
}
189+
job4.id = 3
190+
job4.pre = true
191+
const job5 = () => {
192+
calls.push('job5')
193+
}
194+
job5.id = 2
195+
const job6 = () => {
196+
calls.push('job6')
197+
}
198+
job6.id = 2
199+
job6.pre = true
200+
201+
// We need several jobs to test this properly, otherwise
202+
// findInsertionIndex can yield the correct index by chance
203+
queueJob(job4)
204+
queueJob(job2)
205+
queueJob(job3)
206+
queueJob(job1)
207+
208+
await nextTick()
209+
expect(calls).toEqual(['job1', 'job2', 'job3', 'job6', 'job5', 'job4'])
158210
})
159211

160212
it('preFlushCb inside queueJob', async () => {

Diff for: packages/runtime-core/src/scheduler.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,13 @@ function findInsertionIndex(id: number) {
6969

7070
while (start < end) {
7171
const middle = (start + end) >>> 1
72-
const middleJobId = getId(queue[middle])
73-
middleJobId < id ? (start = middle + 1) : (end = middle)
72+
const middleJob = queue[middle]
73+
const middleJobId = getId(middleJob)
74+
if (middleJobId < id || (middleJobId === id && middleJob.pre)) {
75+
start = middle + 1
76+
} else {
77+
end = middle
78+
}
7479
}
7580

7681
return start

0 commit comments

Comments
 (0)