initLogs 4: JavaScript에서 비동기 함수를 호출할 때 [object Promise]가 표시되는 이유는 무엇입니까?
11617 단어 beginnerswebdevjavascriptprogramming
[object Promise]
입니다. 비동기 기능이 제대로 작동했습니다. 그러나 일반 함수 내에서 비동기 함수를 호출하면 [object Promise]
반환됩니다. 그래서 약속이 없습니다!
왜요?
동기 코드 내에서 비동기 함수를 호출하기 때문에 값으로
[object Promise]
를 얻고 있습니다. 이것은 동기 코드가 한 줄씩 실행되어 비동기 코드가 응답(약속)을 기다리고 응답할 여지가 없음을 의미합니다. 원하는 결과를 얻으려면 호출하는 비동기 함수 주위에 비동기 함수를 래핑해야 합니다.
아래 코드에서는 약속을 반환하는 함수를 만들고 있습니다. 아래
callOpenWeather()
함수는 fetch API를 사용하여 OpenWeatherMap API를 호출하여 feels_like
라는 값을 얻을 수 있습니다. 이것은feels_like
수치입니다.
//Async function to fetch the weather info
// using OpenWeatherMap API
const callOpenWeather = async (url) => {
// Try part when successful return of promise
try {
// Calls the API url, parses to JSON, returns
// feels_like value which is a numerical value.
let callJson = await fetch(url, {mode: 'cors',});
let loadJson = await callJson.json();
return loadJson.main.feels_like;
// Catch part if promise returns an error
} catch(error) {
return error;
}
}
잘못된 방법: 동기 코드 내부의 비동기 함수
이제 위와 상호 작용할 함수를 작성해 보겠습니다
callOpenWeather()
. 아래 코드는 작동하지 않습니다. Promise를 반환하는 callOpenWeather()
함수를 호출해야 하는 경우 아래와 같이 동기 코드 내에서 호출할 수 없습니다. 응답으로 [object Promise]
를 반환합니다.// DOM function to get the data from input and
// use checkWeather function to get the data displayed.
const displayWeather = () => {
const submitButton = document.getElementById('button');
const inputValue = document.getElementById('search');
const infoBox = document.getElementById('info-box');
submitButton.addEventListener('click', () => {
infoBox.style.display = 'grid';
// Use an api key of openweathermap instead of ${apiKey}
// to make this code work.
infoBox.innerText = callOpenWeather(`http://api.openweathermap.org/data/2.5/weather?q=${inputValue.value}&APPID=${apiKey}`);
infoBox.style.boxShadow = '0 0 2px 0 #d3d3d3';
});
}
displayWeather();

infoBox.innerText
가 callOpenWeather()
함수를 호출할 때 displayWeather()
함수는 여전히 일반 동기 함수이기 때문입니다. 이것은 라인이 라인 단위로 실행되고 비동기 함수인 callOpenWeather()
의 값을 기다리지 않는다는 것을 의미합니다. callOpenWeather()
를 호출하고 값(약속)을 얻으려면 비동기식으로 만드십시오. 아래와 같이 async/await 메서드를 사용하여 비동기 함수 내부에 래핑callOpenWeather()
하여 이를 수행할 수 있습니다. 이것은 OpenWeatherMap API에 대한 API 호출을 만들고 결과를 infoBox.innerText
에 설정하고 표시할 수 있도록 결과를 기다립니다.올바른 방법: 비동기 함수로 래핑된 비동기 함수
클릭 이벤트에 대한 이벤트 리스너로 비동기 함수를 래핑하고 있습니다. 이렇게 하면
callOpenWeather()
기능이 제대로 실행되고 OpenWeatherMap API에서 제공한 응답을 반환할 때까지 기다립니다. 아래 솔루션은 async/await 메서드를 사용합니다. await
함수의 응답을 기다리고 promise를 반환하는 callOpenWeather()
키워드의 사용법을 볼 수 있습니다.
// DOM function to get the data from input and
// use checkWeather function to display data.
const displayWeather = () => {
const submitButton = document.getElementById('button');
const inputValue = document.getElementById('search');
const infoBox = document.getElementById('info-box');
// Users "async" keyword on the click event so as to
// make the await at `callOpenWeather()` to wait
// and give back a response (the promise)
submitButton.addEventListener('click', async () => {
infoBox.style.display = 'grid';
// Use an api key of openweathermap instead of ${apiKey}
// to make this code work.
infoBox.innerText = await callOpenWeather(`http://api.openweathermap.org/data/2.5/weather?q=${inputValue.value}&APPID=${apiKey}`);
infoBox.style.boxShadow = '0 0 2px 0 #d3d3d3';
});
}
displayWeather();

이것이 출력으로
[object Promise]
가 붙어있을 때 비동기 코드에서 값을 얻을 수 있는 방법입니다. 이것은 당신이 그것에 대해 생각한다면 완전히 이해되는 시나리오 중 하나입니다. 그러나 우리의 동기적 마음은 그것을 까다로울 수 있습니다.오류를 찾았습니까? 내 글에 대한 피드백이 있습니까? 트위터에서 DM주세요.
이 게시물은 https://www.unsungnovelty.org이라는 제목으로 "initLogs 4: Why am I getting [object Promise] when calling async function in JavaScript"에 처음 게시되었습니다.
Reference
이 문제에 관하여(initLogs 4: JavaScript에서 비동기 함수를 호출할 때 [object Promise]가 표시되는 이유는 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/unsungnovelty/why-am-i-getting-object-promise-when-calling-an-asynchronous-function-in-javascript-30po텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)