#javascript #asynchronous #async-await
#javascript #асинхронный #async-await
Вопрос:
Я пытаюсь использовать результат моей асинхронной функции. Когда я распечатываю result
на консоль, он работает нормально, и я получаю полный объект, напечатанный на консоли.
Однако, когда я пытаюсь распечатать result.data
, он печатает undefined
, даже если data является первым ключом объекта?
Почему я могу распечатать выходные данные функции async, но не ссылаться на значения ее объекта?
$(document).ready(async function() {
const date = 20190313;
const url = 'https://api.jjjacobson.com/dailygames?season=2018-2019-regularamp;date=' date;
let result = await executeCORSRequest(url); //async function
console.log(result);
console.log(result.data);
});
console.log(result.data)
возвращает значение undefined.
Это вывод console.log(result)
:
{"data":{"lastUpdatedOn":"2019-03-14T05:33:37.759Z","games":[{"schedule":{"id":48584,"startTime":"2019-03-13T23:00:00.000Z","endedTime":null,"awayTeam":{"id":95,"abbreviation":"ORL"},"homeTeam":{"id":94,"abbreviation":"WAS"},"venue":{"id":13,"name":"Capital One Arena"},"venueAllegiance":"HOME","scheduleStatus":"NORMAL","originalStartTime":null,"delayedOrPostponedReason":null,"playedStatus":"COMPLETED","attendance":null,"officials":[],"broadcasters":[],"weather":null},"score":{"currentQuarter":null,"currentQuarterSecondsRemaining":null,"currentIntermission":null,"awayScoreTotal":90,"homeScoreTotal":100,"quarters":[{"quarterNumber":1,"awayScore":28,"homeScore":29},{"quarterNumber":2,"awayScore":25,"homeScore":32},{"quarterNumber":3,"awayScore":21,"homeScore":15},{"quarterNumber":4,"awayScore":16,"homeScore":24}]}},{"schedule":{"id":48586,"startTime":"2019-03-13T23:00:00.000Z","endedTime":null,"awayTeam":{"id":84,"abbreviation":"BRO"},"homeTeam":{"id":96,"abbreviation":"OKL"},"venue":{"id":90,"name":"Chesapeake Energy Arena"},"venueAllegiance":"HOME","scheduleStatus":"NORMAL","originalStartTime":null,"delayedOrPostponedReason":null,"playedStatus":"COMPLETED","attendance":null,"officials":[],"broadcasters":[],"weather":null},"score":{"currentQuarter":null,"currentQuarterSecondsRemaining":null,"currentIntermission":null,"awayScoreTotal":96,"homeScoreTotal":108,"quarters":[{"quarterNumber":1,"awayScore":27,"homeScore":19},{"quarterNumber":2,"awayScore":25,"homeScore":23},{"quarterNumber":3,"awayScore":26,"homeScore":38},{"quarterNumber":4,"awayScore":18,"homeScore":28}]}},{"schedule":{"id":48583,"startTime":"2019-03-13T23:30:00.000Z","endedTime":null,"awayTeam":{"id":88,"abbreviation":"DET"},"homeTeam":{"id":92,"abbreviation":"MIA"},"venue":{"id":86,"name":"American Airlines Arena"},"venueAllegiance":"HOME","scheduleStatus":"NORMAL","originalStartTime":null,"delayedOrPostponedReason":null,"playedStatus":"COMPLETED","attendance":null,"officials":[],"broadcasters":[],"weather":null},"score":{"currentQuarter":null,"currentQuarterSecondsRemaining":null,"currentIntermission":null,"awayScoreTotal":74,"homeScoreTotal":108,"quarters":[{"quarterNumber":1,"awayScore":18,"homeScore":30},{"quarterNumber":2,"awayScore":31,"homeScore":24},{"quarterNumber":3,"awayScore":8,"homeScore":33},{"quarterNumber":4,"awayScore":17,"homeScore":21}]}},{"schedule":{"id":48585,"startTime":"2019-03-13T23:30:00.000Z","endedTime":null,"awayTeam":{"id":107,"abbreviation":"MEM"},"homeTeam":{"id":91,"abbreviation":"ATL"},"venue":{"id":20,"name":"StateFarm Arena"},"venueAllegiance":"HOME","scheduleStatus":"NORMAL","originalStartTime":null,"delayedOrPostponedReason":null,"playedStatus":"COMPLETED","attendance":null,"officials":[],"broadcasters":[],"weather":null},"score":{"currentQuarter":null,"currentQuarterSecondsRemaining":null,"currentIntermission":null,"awayScoreTotal":111,"homeScoreTotal":132,"quarters":[{"quarterNumber":1,"awayScore":28,"homeScore":33},{"quarterNumber":2,"awayScore":32,"homeScore":39},{"quarterNumber":3,"awayScore":30,"homeScore":38},{"quarterNumber":4,"awayScore":21,"homeScore":22}]}},{"schedule":{"id":48587,"startTime":"2019-03-14T01:30:00.000Z","endedTime":null,"awayTeam":{"id":101,"abbreviation":"GSW"},"homeTeam":{"id":109,"abbreviation":"HOU"},"venue":{"id":102,"name":"Toyota Center"},"venueAllegiance":"HOME","scheduleStatus":"NORMAL","originalStartTime":null,"delayedOrPostponedReason":null,"playedStatus":"COMPLETED","attendance":null,"officials":[],"broadcasters":[],"weather":null},"score":{"currentQuarter":null,"currentQuarterSecondsRemaining":null,"currentIntermission":null,"awayScoreTotal":106,"homeScoreTotal":104,"quarters":[{"quarterNumber":1,"awayScore":33,"homeScore":23},{"quarterNumber":2,"awayScore":21,"homeScore":29},{"quarterNumber":3,"awayScore":31,"homeScore":26},{"quarterNumber":4,"awayScore":21,"homeScore":26}]}},{"schedule":{"id":48588,"startTime":"2019-03-14T02:00:00.000Z","endedTime":null,"awayTeam":{"id":98,"abbreviation":"UTA"},"homeTeam":{"id":104,"abbreviation":"PHX"},"venue":{"id":98,"name":"Talking Stick Resort Arena"},"venueAllegiance":"HOME","scheduleStatus":"NORMAL","originalStartTime":null,"delayedOrPostponedReason":null,"playedStatus":"COMPLETED","attendance":null,"officials":[],"broadcasters":[],"weather":null},"score":{"currentQuarter":null,"currentQuarterSecondsRemaining":null,"currentIntermission":null,"awayScoreTotal":114,"homeScoreTotal":97,"quarters":[{"quarterNumber":1,"awayScore":25,"homeScore":27},{"quarterNumber":2,"awayScore":28,"homeScore":16},{"quarterNumber":3,"awayScore":25,"homeScore":32},{"quarterNumber":4,"awayScore":36,"homeScore":22}]}}],"references":{"teamReferences":[{"id":84,"city":"Brooklyn","name":"Nets","abbreviation":"BRO","homeVenue":{"id":78,"name":"Barclays Center"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":88,"city":"Detroit","name":"Pistons","abbreviation":"DET","homeVenue":{"id":145,"name":"Little Caesars Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":91,"city":"Atlanta","name":"Hawks","abbreviation":"ATL","homeVenue":{"id":20,"name":"StateFarm Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":92,"city":"Miami","name":"Heat","abbreviation":"MIA","homeVenue":{"id":86,"name":"American Airlines Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":94,"city":"Washington","name":"Wizards","abbreviation":"WAS","homeVenue":{"id":13,"name":"Capital One Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":95,"city":"Orlando","name":"Magic","abbreviation":"ORL","homeVenue":{"id":89,"name":"Amway Center"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":96,"city":"Oklahoma City","name":"Thunder","abbreviation":"OKL","homeVenue":{"id":90,"name":"Chesapeake Energy Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":98,"city":"Utah","name":"Jazz","abbreviation":"UTA","homeVenue":{"id":92,"name":"Vivint Smart Home Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":101,"city":"Golden State","name":"Warriors","abbreviation":"GSW","homeVenue":{"id":95,"name":"Oracle Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":104,"city":"Phoenix","name":"Suns","abbreviation":"PHX","homeVenue":{"id":98,"name":"Talking Stick Resort Arena"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":107,"city":"Memphis","name":"Grizzlies","abbreviation":"MEM","homeVenue":{"id":100,"name":"FedEx Forum"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null},{"id":109,"city":"Houston","name":"Rockets","abbreviation":"HOU","homeVenue":{"id":102,"name":"Toyota Center"},"teamColoursHex":[],"socialMediaAccounts":[],"officialLogoImageSrc":null}],"venueReferences":[{"id":13,"name":"Capital One Arena","city":"Washington, DC","country":"USA","geoCoordinates":null,"capacitiesByEventType":[],"playingSurface":null,"baseballDimensions":[],"hasRoof":null,"hasRetractableRoof":null},{"id":20,"name":"StateFarm Arena","city":"Atlanta, GA","country":"USA","geoCoordinates":null,"capacitiesByEventType":[],"playingSurface":null,"baseballDimensions":[],"hasRoof":null,"hasRetractableRoof":null},{"id":86,"name":"American Airlines Arena","city":"Miami, FL","country":"USA","geoCoordinates":null,"capacitiesByEventType":[],"playingSurface":null,"baseballDimensions":[],"hasRoof":null,"hasRetractableRoof":null},{"id":90,"name":"Chesapeake Energy Arena","city":"Oklahama City, OK","country":"USA","geoCoordinates":null,"capacitiesByEventType":[],"playingSurface":null,"baseballDimensions":[],"hasRoof":null,"hasRetractableRoof":null},{"id":98,"name":"Talking Stick Resort Arena","city":"Phoenix, AZ","country":"USA","geoCoordinates":null,"capacitiesByEventType":[],"playingSurface":null,"baseballDimensions":[],"hasRoof":null,"hasRetractableRoof":null},{"id":102,"name":"Toyota Center","city":"Houston, TX","country":"USA","geoCoordinates":null,"capacitiesByEventType":[],"playingSurface":null,"baseballDimensions":[],"hasRoof":null,"hasRetractableRoof":null}]}}}
Комментарии:
1. попробуйте использовать
JSON.parse(result)
. Возможно, он возвращает строку и как таковой не содержит поляdata
.2. что вы получите, если поставите
console.log(typeof result);
? Если строка, это означает, что ответ в JSON.3. @MatthewVarga вот и все! Спасибо
4. попробуйте
console.log(result[0].data)
Ответ №1:
Проверьте, result
является ли это строкой, которую вы должны проанализировать, используя JSON.parse()
:
let obj = JSON.parse(result);
Позже
console.log(obj.data)