- From: Thomas Steiner via GitHub <sysbot+gh@w3.org>
- Date: Wed, 07 Aug 2019 09:11:51 +0000
- To: public-device-apis-log@w3.org
tomayac has just created a new issue for https://github.com/w3c/wake-lock:
== WakeLock.request() returns a promise that never resolves ==
When playing with the [new API](https://bugs.chromium.org/p/chromium/issues/detail?id=257511#c87), implemented by @rakuco, I intuitively started with this:
```js
/* 🚫 Code sample 1 */
(async () => {
const controller = new AbortController();
const signal = controller.signal;
try {
await WakeLock.request('screen', {signal});
// This will never be reached
console.log('Wake Lock is active');
} catch (e) {
// This will never be reached
if (e.name === 'AbortError') {
console.log('All fine, Wake Lock aborted');
} else {
console.error(e.name, e.message);
}
}
// This will never be reached
window.setTimeout(() => {
controller.abort();
}, 5000);
})();
```
I soon realized that I can't `await` a never resolving promise, so I switched to the below, which works as intended, but results in an ugly uncaught promise error:
`Uncaught (in promise) DOMException`:
```js
/* 🚫 Code sample 2 */
(async () => {
const controller = new AbortController();
const signal = controller.signal;
try {
// Don't `await`
/* await */ WakeLock.request('screen', {signal});
// This will be reached now
console.log('Wake Lock is active');
} catch (e) {
// This will never be reached
if (e.name === 'AbortError') {
console.log('All fine, Wake Lock aborted');
} else {
console.error(e.name, e.message);
}
}
// This will be reached now
window.setTimeout(() => {
controller.abort();
}, 5000);
})();
```
In order to avoid an uncaught promise, the final working code I settled upon is the following, with the `catch()` chained to the `WakeLock.request()`, which is a little ugly as well:
```js
/* ✅ Code sample 3 */
(async () => {
const controller = new AbortController();
const signal = controller.signal;
// Don't `await`
WakeLock.request('screen', {signal})
// Chain a `catch()`
.catch((e) => {
if (e.name === 'AbortError') {
console.log('All fine, Wake Lock aborted');
} else {
console.error(e.name, e.message);
}
});
// This will be reached now
console.log('Wake Lock is active');
// This will be reached now
window.setTimeout(() => {
controller.abort();
}, 5000);
})();
```
Unless I am completely wrong (which is easily possible), the intuitive (by my intuition at least) *Code sample 1* could be made work if the promise returned as a result of running the steps in [§ 6.3](https://w3c.github.io/wake-lock/#request-static-method) would resolve if (and only if) `active`, i.e., the result of [§ 7.4](https://w3c.github.io/wake-lock/#dfn-acquire-a-wake-lock), is `true`. Thoughts?
Please view or discuss this issue at https://github.com/w3c/wake-lock/issues/226 using your GitHub account
Received on Wednesday, 7 August 2019 09:11:53 UTC