held.https.any.js (2725B)
1 // META: title=Web Locks API: Lock held until callback result resolves 2 // META: script=resources/helpers.js 3 // META: global=window,dedicatedworker,sharedworker,serviceworker 4 5 'use strict'; 6 7 // For uncaught rejections. 8 setup({allow_uncaught_exception: true}); 9 10 function snooze(t, ms) { return new Promise(r => t.step_timeout(r, ms)); } 11 12 promise_test(async t => { 13 const res = uniqueName(t); 14 const p = navigator.locks.request(res, lock => 123); 15 assert_equals(Promise.resolve(p), p, 'request() result is a Promise'); 16 assert_equals(await p, 123, 'promise resolves to the returned value'); 17 }, 'callback\'s result is promisified if not async'); 18 19 promise_test(async t => { 20 const res = uniqueName(t); 21 // Resolved when the lock is granted. 22 let granted; 23 const lock_granted_promise = new Promise(r => { granted = r; }); 24 25 // Lock is held until this is resolved. 26 let resolve; 27 const lock_release_promise = new Promise(r => { resolve = r; }); 28 29 const order = []; 30 31 navigator.locks.request(res, lock => { 32 granted(lock); 33 return lock_release_promise; 34 }); 35 await lock_granted_promise; 36 37 await Promise.all([ 38 snooze(t, 50).then(() => { 39 order.push('1st lock released'); 40 resolve(); 41 }), 42 navigator.locks.request(res, () => { 43 order.push('2nd lock granted'); 44 }) 45 ]); 46 47 assert_array_equals(order, ['1st lock released', '2nd lock granted']); 48 }, 'lock is held until callback\'s returned promise resolves'); 49 50 promise_test(async t => { 51 const res = uniqueName(t); 52 // Resolved when the lock is granted. 53 let granted; 54 const lock_granted_promise = new Promise(r => { granted = r; }); 55 56 // Lock is held until this is rejected. 57 let reject; 58 const lock_release_promise = new Promise((_, r) => { reject = r; }); 59 60 const order = []; 61 62 navigator.locks.request(res, lock => { 63 granted(lock); 64 return lock_release_promise; 65 }); 66 await lock_granted_promise; 67 68 await Promise.all([ 69 snooze(t, 50).then(() => { 70 order.push('reject'); 71 reject(new Error('this uncaught rejection is expected')); 72 }), 73 navigator.locks.request(res, () => { 74 order.push('2nd lock granted'); 75 }) 76 ]); 77 78 assert_array_equals(order, ['reject', '2nd lock granted']); 79 }, 'lock is held until callback\'s returned promise rejects'); 80 81 promise_test(async t => { 82 const res = uniqueName(t); 83 let callback_called = false; 84 await navigator.locks.request(res, async lock => { 85 await navigator.locks.request(res, {ifAvailable: true}, lock => { 86 callback_called = true; 87 assert_equals(lock, null, 'lock request should fail if held'); 88 }); 89 }); 90 assert_true(callback_called, 'callback should have executed'); 91 }, 'held lock prevents the same client from acquiring it');