从节点模块

时间:2018-09-07 16:08:31

标签: node.js module async-await es6-promise

我正在开发一个vue应用程序,并且编写了一个模块,该模块使用axios调用mySportsFeed.com以获取数据。我的问题是,由于axios的异步特性,我得到的是承诺而不是数据。我尝试了几种不同的方法来解决此问题,但无济于事。我希望有人能够指出我的错误。代码是:

vue.js

//====== Get Standings From MySportsFeeds Site ======================================== //
  url = `https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/division_team_standings.json?teamstats=W,L,GB,Win %`;

  mySportsFeeds.feedsData(url)
    .then(function(response) {
      this.standings = response;
      console.log(`Standings is : ${this.standings}`);
  });

  // ======= end Standings ================================================ //

mySportsFeeds.js:

    module.exports = {
  /* jshint ignore:start */
  feedsData: async function(url) {
    url = encodeURI(url); // Format the URI

    return (await axios.get(url, config)).data.divisionteamstandings.division;
  }

控制台输出:

Array(6)[{…},{…},{…},{…},{…},{…}] mySportsFeeds.js:29

依据是:[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象] vue.js:106

vue面板显示: 排名:数组[0]

Console Output

如您所见,this.standings是不确定的?任何指导,不胜感激。...

更新的工作代码: vue.js:

 //====== Get Standings From MySportsFeeds Site =========================== //
      url = `https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/division_team_standings.json?teamstats=W,L,GB,Win %`;

      /* jshint ignore:start */
      // Note: We use the arrow function here because "this" is defined by where
      // getStandings() is called (the vue instance) not by where it is used.
      let getStandings = async () => {
        this.standings = await mySportsFeeds.feedsData(url);
      };
      /* jshint ignore:end */

      getStandings();

mySportsFeeds.js:

module.exports = {
  /* jshint ignore:start */
  feedsData: async function(url) {
    url = encodeURI(url); // Format the URI

    return (await axios.get(url, config)).data.divisionteamstandings.division;
  }
  /* jshint ignore:end */
};

0 个答案:

没有答案