簡體   English   中英

如何在promise.then()中檢索對此的引用?

[英]how can I retrieve a reference to this in a promise.then ()?

javascript / Node.js

如何在promise.then中檢索對此對象的引用?

var controller = new MyController(params);

controller.action_send();

/////////////////////////////////

class MyController{

    constructor(params)
    {
        this.params = params;
    }

    action_send()
    {
        var promise = ext_lib.send();


        promise.then(
            function(details) {

                this.action_save(details);
                //(node:27014) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'action_save' of undefined
           });
   }

    action_save(details)
    {  
     save (this.params, details);
    }   
}

PHPStorm警告說,警告您不要嘗試通過此方法引用ECMAScript類成員的常見錯誤。 非lambda的嵌套函數中的限定符。 嵌套函數(不是lambda)中的this是函數自己的“ this”,與外部類無關。

從現在開始

您想使用箭頭功能:( (details) => {...} 這將使作用域與函數外部的作用域相同,因此this應該是您的類。

我還建議您查找function語法和=>語法之間的區別,也許有人可以比我更好地解釋它。

使用arrow function

與常規函數不同,箭頭函數不會綁定this 相反,這是按詞法綁定的(即,其含義與其原始上下文保持一致)。

這里有更多的細節吧箭頭功能

只需添加上述答案,這就是您的代碼應為的樣子

promise()
.then(function (results) {
  }.bind(this)
).catch(...);

確保您的綁定在關閉then()之前

暫無
暫無

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

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