JavaScript promise : Deep nested context with bind(this)

标签 javascript promise ecmascript-6 es6-promise

因为我使用的原型(prototype)具有调用同一原型(prototype)中其他函数的函数,所以我必须使用 this 引用该方法。

问题 this创建:

但正因为如此,我必须保留一个上下文才能使用 this这让我变得非常丑陋.bind(this)墙壁。

这是我为笑而制作的简化示例。

Killmyself.prototype.fireLeMissles = function () {

    return new Promise(function(resolve,reject) {
        this.anotherFunction(param).then(function(result) {

        someList.forEach(function(item) {
          this.fireLeMissles().then(function(anotherResult){
            promiseList.push(anotherResult)
          })
        },this);
        Promise.all(promiseList).then(function(promiseItem){
          childPlacesIds.forEach(function(childPlaceId) {
            //Do Other Stuff
          },this);
        });
      resolve(result);
    }.bind(this).catch(function(err){
      console.log("Yea, life sucks sometimes.")
    }));
  }.bind(this));
}

Killmyself.prototype.another = function(){
   //Other stuff
}

您可以看到因为调用了同一原型(prototype)中的函数,例如 this.anotherFunction( ...和this.fireLeMissles( ...我必须对上下文进行深度保存,现在(在我更大的版本中)这使得这段代码难以使用。

问题:

这是一个“习惯于 JavaScript 更难的方面”的事情吗?还是你经验丰富的开发人员看到了可以避免像这样的深度绑定(bind)的简单方法?

最佳答案

如果您使用 ES6 ,您可以受益于arrow functions ,它保留了上下文。

var counter = function () {
    this.count = 0;
    setInterval( () => { // arrow function
        console.log(this.count++); // context is preserved
    }, 1000)
}
var counter = new counter();

因此,您的代码将变为:
Killmyself.prototype.fireLeMissles = function() {
    return new Promise((resolve, reject) => {
        this.anotherFunction(param).then(result => {
            someList.forEach(item => {
                this.fireLeMissles().then(anotherResult => {
                    promiseList.push(anotherResult)
                });
            });
            Promise.all(promiseList).then(promiseItem => {
                childPlacesIds.forEach(childPlaceId => {
                    //Do Other Stuff
                });
            });
            resolve(result);
        }).catch(err => {
            console.log("Yea, life sucks sometimes.")
        });
    });
}

对于 ES5 ,您可以使用 .bind就像你做的那样,或者你可以分配this到具有所需上下文的函数中的其他内容,然后在内部函数中使用该变量。
Killmyself.prototype.fireLeMissles = function() {
    var self = this; /// use `self` instead of `this` from now on.
    return new Promise(function(resolve, reject) {
        self.anotherFunction(param).then(function(result) {
            someList.forEach(function(item) {
                self.fireLeMissles().then(function(anotherResult) {
                    promiseList.push(anotherResult)
                })
            });
            Promise.all(promiseList).then(function(promiseItem) {
                childPlacesIds.forEach(function(childPlaceId) {
                    //Do Other Stuff
                });
            });
            resolve(result);
        }).catch(function(err) {
            console.log("Yea, life sucks sometimes.")
        });
    });
}

关于JavaScript promise : Deep nested context with bind(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735449/

相关文章:

node.js - Intellij NodeJs 6.4.0 意外 token 导出

javascript - 在 try block 中分配值的最佳方法

javascript - ConstructorFunc.property 与 ConstructorFunc.prototype.property

javascript - npm 错误!不支持的 URL 类型 "workspace:": workspace:*

javascript - 我的异步请求在 Express 中不起作用

javascript - Bluebird Promisify execFile 无法得到解决的 promise

javascript - 如何让最后一个网格项填满网格剩余空间?

php - 如何在 PHP 中实现屏幕抓取工具?

javascript - 当嵌套函数仍在运行时暂停外部函数

javascript - 在 ES6 中, 'generator' 实际上如何在 V8 引擎内暂停?