如何编写适合Promise.resolve()的诺言的多票?

发布于 2025-02-12 08:59:46 字数 2409 浏览 0 评论 0原文

我试图写一个诺言多填充,以更好地了解诺言。 我已经搜索了互联网,并找到了一个可以在某种程度上理解的代码。

function CustomPromise(executor) {
var state=PENDING;
var value = null;
var handlers=[];
var catchers = [];

function resolve(result) {
    if(state!==PENDING) return;

    state=FULFILLED;
    value = result;

    handlers.forEach((h)=>h(value));    //this line
}

function reject(error) {
    if(state!==PENDING)return;

    state=REJECTED;
    value=error;
    catchers.forEach(c=>c(value));  // this line
}

this.then = function(successCallback) {
    if(state === FULFILLED) {
        successCallback(value);
    }else {
        handlers.push(successCallback);
    }
    return this;
}

this.catch = function(failureCallback) {
    if(state===REJECTED){
        failureCallback(value)
    } else {
        catchers.push(value);
    }
}
executor(resolve,reject);
}

即使在这方面,我也无法理解处理人员和捕手的使用。据说他们是在未实现或拒绝承诺的情况下。解释这两条线也将有所帮助。 现在,上述实现的实际问题是,当使用Let p1 = Promise.resolve(“ Hello World”);时,它不适用于使用。我尝试将其转换为基于课堂的,但我无法做到这一点。 我的尝试:

class CustomPromise {
constructor(callback){
    this.state = PENDING;
    this.executor = callback;
    this.value = null;
    this.handlers = [];
    this.catchers = [];
    this.then = function(successCallback) {
        if(this.state === FULFILLED) {
            successCallback(this.value);
        }else {
            this.handlers.push(successCallback);
        }
        return this;
    };

    this.catch = function(failureCallback) {
        if(this.state===REJECTED){
            failureCallback(this.value)
        } else {
            this.catchers.push(this.value);
        }
    };
}

static resolve(result) {
    if(this.state!==PENDING) return;

    this.state=FULFILLED;
    this.value = result;

    this.handlers.forEach((h)=>h(this.value));
    // return new CustomPromise( function ( fulfil ) {
    //     fulfil( value );
    // });
}

static reject(error) {
    if(this.state!==PENDING)return;

    this.state=REJECTED;
    this.value=error;
    this.catchers.forEach(c=>c(this.value));
}

// executor(resolve,reject);
}

有人可以纠正功能方法,以便它适用于ustompromise.resolve()方案或基于我类的方法中的校正。 编辑:尝试custompromise.prototype.resolve = function(error){...} 仍然有相同的错误custompromise.resolve不是函数 edit2:在基于类的方法中,我无法实现 executor 回调。我只想使用Promise.resolve()的案例工作方法之一

I'm trying to write a promise polyfill to get a better understanding of promise.
I've searched the internet and found a code which I'm able to understand to some extent.

function CustomPromise(executor) {
var state=PENDING;
var value = null;
var handlers=[];
var catchers = [];

function resolve(result) {
    if(state!==PENDING) return;

    state=FULFILLED;
    value = result;

    handlers.forEach((h)=>h(value));    //this line
}

function reject(error) {
    if(state!==PENDING)return;

    state=REJECTED;
    value=error;
    catchers.forEach(c=>c(value));  // this line
}

this.then = function(successCallback) {
    if(state === FULFILLED) {
        successCallback(value);
    }else {
        handlers.push(successCallback);
    }
    return this;
}

this.catch = function(failureCallback) {
    if(state===REJECTED){
        failureCallback(value)
    } else {
        catchers.push(value);
    }
}
executor(resolve,reject);
}

Even in this I'm unable to understand the use of handlers and catchers. It was said that they are for situation when promise is not fulfilled or rejected. Explaining these two lines will also help.
Now, the actual issue with above implementation is it doesn't work for when used like let p1 = Promise.resolve("Hello World");. I have tried converting it to class based but I'm unable to do that.
My attempt:

class CustomPromise {
constructor(callback){
    this.state = PENDING;
    this.executor = callback;
    this.value = null;
    this.handlers = [];
    this.catchers = [];
    this.then = function(successCallback) {
        if(this.state === FULFILLED) {
            successCallback(this.value);
        }else {
            this.handlers.push(successCallback);
        }
        return this;
    };

    this.catch = function(failureCallback) {
        if(this.state===REJECTED){
            failureCallback(this.value)
        } else {
            this.catchers.push(this.value);
        }
    };
}

static resolve(result) {
    if(this.state!==PENDING) return;

    this.state=FULFILLED;
    this.value = result;

    this.handlers.forEach((h)=>h(this.value));
    // return new CustomPromise( function ( fulfil ) {
    //     fulfil( value );
    // });
}

static reject(error) {
    if(this.state!==PENDING)return;

    this.state=REJECTED;
    this.value=error;
    this.catchers.forEach(c=>c(this.value));
}

// executor(resolve,reject);
}

Can someone correct the functional approach so that it works for CustomPromise.resolve() scenario or correction in my class based approach will also be appreciated.
EDIT: Tried CustomPromise.prototype.resolve = function(error) {...}
still getting same error CustomPromise.resolve is not a function
EDIT2 : In class based approach I'm unable to implement executor callback. I just want either one of the approach to work for case like Promise.resolve()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本王不退位尔等都是臣 2025-02-19 08:59:46

要扩展customPromise的第一个(工作)版本,请在您所拥有的(非工作)类中添加您似乎一直在注释的代码中尝试的代码。但这有两个小问题。尽管如此,使用新的自定义promise的想法是正确的:

CustomPromise.resolve = value => new CustomPromise(fulfil => fulfil(value));
CustomPromise.reject = error => new CustomPromise((_, reject) => reject(error));

因此,如果将其添加到自定义函数>函数定义下方,则它将工作。

其次,由于Catchers应该具有回调函数,因此您不应将value推向其,而是failurecallback

const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function CustomPromise(executor) {
    var state=PENDING;
    var value = null;
    var handlers=[];
    var catchers = [];

    function resolve(result) {
        if(state!==PENDING) return;

        state=FULFILLED;
        value = result;

        handlers.forEach((h)=>h(value));
    }

    function reject(error) {
        if(state!==PENDING)return;

        state=REJECTED;
        value=error;
        catchers.forEach(c=>c(value));
    }

    this.then = function(successCallback) {
        if(state === FULFILLED) {
            successCallback(value);
        }else {
            handlers.push(successCallback);
        }
        return this;
    }

    this.catch = function(failureCallback) {
        if(state===REJECTED){
            failureCallback(value)
        } else {
            catchers.push(failureCallback); // Fix
        }
    }
    executor(resolve,reject);
}

// Added:
CustomPromise.resolve = value => new CustomPromise(fulfil => fulfil(value));
CustomPromise.reject = error => new CustomPromise((_, reject) => reject(error));

// Demo
let p = CustomPromise.resolve(42);
let q = CustomPromise.reject("custom error");
p.then(value => console.log("p", value));
q.catch(error => console.log("q", error));

免责声明:此polyfill不符合 promises/a+规格让我们符合<<<<<<代码> Promise 。

它遇到的一些问题:

  • 它允许然后回调同步执行。 然后,回调绝不应同步执行,但始终通过排队的作业(即异步)来调用。
  • catch方法错误地返回未定义。它应该回报承诺。
  • 然后,然后方法错误地返回了与所谓的相同的承诺。它应该返回一个不同的承诺,以回调将返回的价值解决。
  • 然后,然后方法忽略了第二个参数。它应该采用第二个功能,该功能应用作拒绝回调(例如catch)。
  • 当承诺通过当时解决时,当时的诺言被错误地用作满足价值。这不是应该如何工作的方式。诺言的一个非常重要的方面是,诺言,即当诺言决心另一个诺言(或当时的诺言)时,它被“锁定在”到第二个诺言,以便遵循该方式第二个承诺解决了。

有许多正确的实现。我发布了自己的诺言/A+兼容实施在此答案中。它没有Resolve拒绝静态方法,但它需要与上面给出的附加代码相同。

To extend the first (working) version of CustomPromise, add the code you seem to have been trying with in commented-out code in the (non-working) class-version you had. But it had two little problems. Still, the idea to use new CustomPromise is the right one:

CustomPromise.resolve = value => new CustomPromise(fulfil => fulfil(value));
CustomPromise.reject = error => new CustomPromise((_, reject) => reject(error));

So if you add that below your CustomPromise function definition, it'll work.

Secondly, as catchers is supposed to have callback functions, you should not push value to it, but failureCallback:

const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function CustomPromise(executor) {
    var state=PENDING;
    var value = null;
    var handlers=[];
    var catchers = [];

    function resolve(result) {
        if(state!==PENDING) return;

        state=FULFILLED;
        value = result;

        handlers.forEach((h)=>h(value));
    }

    function reject(error) {
        if(state!==PENDING)return;

        state=REJECTED;
        value=error;
        catchers.forEach(c=>c(value));
    }

    this.then = function(successCallback) {
        if(state === FULFILLED) {
            successCallback(value);
        }else {
            handlers.push(successCallback);
        }
        return this;
    }

    this.catch = function(failureCallback) {
        if(state===REJECTED){
            failureCallback(value)
        } else {
            catchers.push(failureCallback); // Fix
        }
    }
    executor(resolve,reject);
}

// Added:
CustomPromise.resolve = value => new CustomPromise(fulfil => fulfil(value));
CustomPromise.reject = error => new CustomPromise((_, reject) => reject(error));

// Demo
let p = CustomPromise.resolve(42);
let q = CustomPromise.reject("custom error");
p.then(value => console.log("p", value));
q.catch(error => console.log("q", error));

Disclaimer: this polyfill is not compliant with the Promises/A+ specification let be it would be compliant with the ECMAScript specification for Promise.

Some of the problems it has:

  • It allows the then callback to be executed synchronously. The then callback should never be executed synchronously, but always be called via a queued job (i.e. asynchronously).
  • The catch method wrongly returns undefined. It should return a promise.
  • The then method wrongly returns the same promise as it is called on. It should return a different promise, that resolves with the value that will be returned by the callback.
  • The then method ignores a second argument. It should take a second function which should serve as a rejection callback (like catch).
  • When the promise is resolved with a thenable, the thenable is wrongly used as fulfillment value. This is not how it is supposed to work. A very important aspect of promises, is that promises chain, i.e. when a promise resolves to another promise (or thenable), it gets "locked in" to that second promise, so that it will follow the way that second promise resolves.

There are many correct implementations to be found. I posted my own Promises/A+ compliant implementation in this answer. It does not have the resolve and reject static methods, but it would require the same additional code as given above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文