
Almost a year after first working on this, it's finally done: an implementation of Promises for LibJS! :^) The core functionality is working and closely following the spec [1]. I mostly took the pseudo code and transformed it into C++ - if you read and understand it, you will know how the spec implements Promises; and if you read the spec first, the code will look very familiar. Implemented functions are: - Promise() constructor - Promise.prototype.then() - Promise.prototype.catch() - Promise.prototype.finally() - Promise.resolve() - Promise.reject() For the tests I added a new function to test-js's global object, runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs(). By design, queued jobs normally only run after the script was fully executed, making it improssible to test handlers in individual test() calls by default [2]. Subsequent commits include integrations into LibWeb and js(1) - pretty-printing, running queued promise jobs when necessary. This has an unusual amount of dbgln() statements, all hidden behind the PROMISE_DEBUG flag - I'm leaving them in for now as they've been very useful while debugging this, things can get quite complex with so many asynchronously executed functions. I've not extensively explored use of these APIs for promise-based functionality in LibWeb (fetch(), Notification.requestPermission() etc.), but we'll get there in due time. [1]: https://tc39.es/ecma262/#sec-promise-objects [2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
37 lines
1.1 KiB
JavaScript
37 lines
1.1 KiB
JavaScript
test("length is 1", () => {
|
|
expect(Promise).toHaveLength(1);
|
|
});
|
|
|
|
describe("errors", () => {
|
|
test("must be called as constructor", () => {
|
|
expect(() => {
|
|
Promise();
|
|
}).toThrowWithMessage(TypeError, "Promise constructor must be called with 'new'");
|
|
});
|
|
|
|
test("executor must be a function", () => {
|
|
expect(() => {
|
|
new Promise();
|
|
}).toThrowWithMessage(TypeError, "Promise executor must be a function");
|
|
});
|
|
});
|
|
|
|
describe("normal behavior", () => {
|
|
test("returns a Promise object", () => {
|
|
const promise = new Promise(() => {});
|
|
expect(promise).toBeInstanceOf(Promise);
|
|
expect(typeof promise).toBe("object");
|
|
});
|
|
|
|
test("executor is called with resolve and reject functions", () => {
|
|
let resolveFunction = null;
|
|
let rejectFunction = null;
|
|
new Promise((resolve, reject) => {
|
|
resolveFunction = resolve;
|
|
rejectFunction = reject;
|
|
});
|
|
expect(typeof resolveFunction).toBe("function");
|
|
expect(typeof rejectFunction).toBe("function");
|
|
expect(resolveFunction).not.toBe(rejectFunction);
|
|
});
|
|
});
|