将承诺值传递给标头

时间:2016-11-23 13:04:44

标签: javascript ecmascript-6

我正在尝试在标头中传递promise值,但我无法这样做。

class test{

  constructor(auth_key,auth_secret){
    this.auth_key = auth_key;
    this.auth_secret = auth_secret;
    console.log("============In class test============");
    this.authtoken = this.init().then(function(value){
        return value;
    });
  }

  init(){
    console.log("============In init function============"+this.auth_key);
    let postData = {};
    return this.requestStt('test','POST',postData).then((response) => {
        if (response.status == 200) {
            return response.body.then((response) => {
                //console.log(response.token);
                let apiResp = {stt_token:response.token}
                return apiResp;
             });
        }else {
            console.log(response)
        }
    });
  }

  gettoken(){
    console.log(this.authtoken)
    var reqHeaders = new Headers({
      "Accept":"application/json",
      "Content-Type": "application/json; charset=UTF-8",
      "token":this.authtoken,
      });
  }
}

获取错误,因为this.authtoken是一个承诺对象。

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:1)

如果你重写gettoken,如下所示:

gettoken(){
    return this.authtoken.then(function(token) {
      return new Headers({
        "Accept":"application/json",
        "Content-Type": "application/json; charset=UTF-8",
        "token":token,
      });
   })
}
当然,

要使用这些标题,您需要执行类似

的操作
xxx.gettoken().then(function(headers) {
    // whatever you do with headers goes here
});