ITADN

`Promise.create()` instead of `Promise.withResolvers()`

#17Closedcoderaiser 创建于 2023-07-11
C
coderaisercommented
JavaScript already have `Object` constructor which has two ways to create a new instance: - ✅ `new Object()`; - ✅ `Object.create()`; > **The `Object.create()` static method creates a new object, using an existing object as the prototype of the newly created object.** > > **(c) [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)** ```js const normalObj = new Object(); // create a normal object const nullProtoObj = Object.create(null); // create an object with "null" prototype ``` In a similar way we have two ways to create a `Promise`, using: - ✅ `new Promise((resolve, reject) => {})` - creates `Promise` using constructor which receives `resolve, reject` callback; - ✅ `const [promise, resolve, reject] = Promise.create()` - creates `Promise` and returns `resolve, reject` in a flat way, without using any callbacks; So the whole code: ```js // old way const promise1 = new Promise((resolve, reject) => {}); // new way const [promise2, resolve, reject] = Promise.create() ``` This naming is pretty obvious for JavaScript developers, and keeps language consistent. That would be fantastic API, and here is polyfill: ```js Promise.prototype.create = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }) return [promise, resolve, reject]; } ``` Inspired by: #2, #16 And I absolutely disagree with: > This is just a POJO that contains a promise along with its resolve and reject functions. We don't really need a concise name for that thing because 99 times out of 100 people are going to just destructure it anyway. > POJO in Java stands for Plain Old Java Object. It is an ordinary object, which is not bound by any special restriction. Create function returns not a POJO, it creates a promise with it’s controls outside. Control `resolve` fulfills promise, `reject` rejects. It flattens a way to create a Promise, but this is a way to create such thing as Promise, so: ```js const [readFile, onRead, onError] = Promise.create(); ```
关闭于 2023-07-11 4 条评论