如何在ES6中执行超级类的承诺

时间:2017-04-29 11:13:25

标签: ecmascript-6 es6-promise es6-class es6-modules

我在Parent类中有一个承诺,每当我从子类调用promise时,它返回undefined,而不是执行promise并返回结果。

从" ./ secretToken";

导入{newsApiKey为APIKEY,newUrl为APIURL}
class News{

 constructor(){
    this.token = APIKEY;
    this.url = APIURL;
    this.source = 'bbc-news&';

 }

 topNews(){
   const bbcNews = fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`);
   bbcNews.then(response => {
     if (!response.ok) {
            throw Error(response.statusText);
        }
    return response.json()
   })
   .then(json => {
     console.log(json.articles);
     return json.articles;
   })
   .catch((err) => {
      return err.message;
    });
 }  
}


export { News as default};

儿童类

import News from "./news";

class StickyNote extends News{

    displayNews(){
      let bbcNews = super.topNews(); // It is  returning only undefined
      if (typeof bbcNews != 'undefined') {
        console.log(bbcNews); //
      }

    }
}

1 个答案:

答案 0 :(得分:2)

topNews永远不会返回任何内容,因此调用它的结果是undefined

你可能想要return

topNews() {
    const bbcNews = fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`);
    return bbcNews.then(response => {
//  ^^^^^^
        if (!response.ok) {
          throw Error(response.statusText);
        }
        return response.json()
      })
      .then(json => {
        console.log(json.articles);
        return json.articles;
      })
      .catch((err) => {
        return err.message;
      });
}

另请注意,displayNews需要使用收到的承诺:

displayNews(){
  super.topNews().then(articles => {
    // ...use articles
  });
}

(通常情况下,您在消费终点也有catch,但是当您将拒绝转换为决议时......)

注意:该代码中有一些反模式:它将拒绝转换为带有错误消息的分辨率。 使用承诺的任何东西都不会被拒绝,只有具有不同返回类型的分辨率(无论json.articles是什么或字符串)。一般来说,允许拒绝传播并在整个链的最终消费点处理它们会更好(我相信,在你的例子中,displayNews)。您可以转换其内容,但不能将其从拒绝转换为解决方案。

FWIW,我可能会像这样重写:

topNews() {
  return fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`)
    .catch(_ => {
      throw new Error("network error");
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(data => {                  // "data", not "json" -- it's not JSON anymore
      return data.articles;
    });
}

...确保来电者获得文章的分辨率,或者使用Error拒绝,所以:

displayNews(){
  super.topNews()
    .then(articles => {
      // ...use articles
    })
    .catch(err => {
      // ...show error
    });
}