簡體   English   中英

從Promise訪問“ this”之外的JavaScript

[英]Access JavaScript Outside 'this' from Promise

我什至不知道該怎么表達我的問題,在我完全搞清楚之前,這是我的代碼:

className.prototype.requestData = function (start, end) {
    client.server.functionName(parameters)
        .done(function (msg) {
            if (msg) {                
                this.process(msg); //this belongs to client, not className as I want
            }
        })
        .fail(function (error) {
            console.log('failed: ' + error);
        });
}

如您所見,我需要調用process對返回的數據進行操作,並且我不想使用為它定義的變量,我想使用this ,並且我猜這是不可能的,是否有更好的方法可以實現我的目標?

謝謝

要做到這一點的方法之一是存儲this變量中,以便日后訪問它:

className.prototype.requestData = function (start, end) {
    var _this = this;
    client.server.functionName(parameters)
        .done(function (msg) {
            if (msg) {                
                _this.process(msg); //this belongs to className as you want
            }
        })
        .fail(function (error) {
            console.log('failed: ' + error);
        });
}

使用bind

className.prototype.requestData = function (start, end) {
    client.server.functionName(parameters)
        .done(function (msg) {
            if (msg) {                
                this.process(msg); //this belongs to className as you want
            }
        }.bind(this))
        .fail(function (error) {
            console.log('failed: ' + error);
        });
}

否則,請使用箭頭功能(在其他答案中提到),但是如果您需要訪問this es,更多詳細信息和示例,則第一個將是您最好的選擇: https : //medium.freecodecamp.org/learn-es6-the-塗料途徑第二部分箭頭功能和此關鍵字381ac7a32881

如果您使用的是ES6,則可以使用async / await:

className.prototype.requestData = async function (start, end) {
    try {
        let result = await client.server.functionName(parameters);
        if (result ) {                
            this.process(result);
        }
    } catch (err) {
        console.log('failed: ' + err);
    }
}

如果要“鏈接”它們,可以執行以下操作:

try {
    let result = await client.server.functionName(parameters);
    if (result) {                
        this.process(result);
    }
    // You can just call each in succession
    let other_result = await client.server.someOtherAsyncFunc(other_params);
    if(other_result) {
        // Do more stuff
    }
} catch (err) {
    console.log('failed: ' + err);
}

// You can still call more promise-based functions after the try-catch block
let some_result = await client.server.yetAnotherAsyncFunc(more_params);
// Do other stuff with some_result

假設您在支持它們的環境中(此時基本上不是IE,則可以使用Arrow Functions) 從鏈接:

在全局上下文中執行時,箭頭函數不會重新定義其自身。 而是使用封閉詞法上下文的this值,等效於將其視為封閉值。

className.prototype.requestData = function (start, end) {
    client.server.functionName(parameters)
        .done((msg) => {
            if (msg) {                
                this.process(msg); //this belongs to client, not className as I want
            }
        })
        .fail((error) => {
            console.log('failed: ' + error);
        });
}

如果沒有箭頭功能,則必須將其存儲在閉包變量中。 否則是不可能的。

className.prototype.requestData = function (start, end) {
  var thisClassName = this;

  client.server.functionName(parameters)
    .done(function (msg) {
      if (msg) {
        thisClassName.process(msg);
      }
    })
    .fail(function (error) {
      console.log('failed: ' + error);
    });
}

// or in ES6 use arrow-function:

className.prototype.requestData = function (start, end) {
  client.server.functionName(parameters)
    .done((msg) => {
      if (msg) {
        // this is the instance of className.
        this.process(msg);
      }
    })
    .fail((error) => {
      console.log('failed: ' + error);
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM