如何传递 Promise 执行器数据?

How can you pass a Promise executor data?

有没有办法在不依赖闭包的情况下将 params 带入 Promise 的主体?我宁愿不必使用 var self = this;

function Service(n) {
    this.n = n;
}
Service.prototype = {
    get: function (params) {
        var self = this;
        return new Promise(function(resolve, reject){
            if (params[self.n]) {
                resolve("Service " + self.n);
            } else {
                reject("Service " + self.n);
            }
        });
    }
}

您可以使用箭头函数绕过额外的 var self = this

来自Arrow Function MDN

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.

以下是它在您的示例中的使用方式:

function Service(n) {
    this.n = n;
}
Service.prototype = {
    get: function (params) {
        return new Promise((resolve, reject) => {
            if (params[this.n]) {
                resolve("Service " + this.n);
            } else {
                reject("Service " + this.n);
            }
        });
    }
}

您实际上可以改为立即创建 resolved/rejected 承诺:

Service.prototype = {
    get: function (params) {
        if (params[this.n]) {
            return Promise.resolve("Service " + this.n);
        }

        return Promise.reject("Service " + this.n);
    }
}

参考文献:

您可以使用 ES7 async 函数。

function Service(n) {
    this.n = n;
}
Service.prototype = {
    get: async function (params) {
        if (params[this.n]) {
            return "Service " + this.n;
        } else {
            throw "Service " + this.n;
        }
    }
}

我认为闭包没有错。该代码实际上将转换为依赖于闭包的代码。