아래 처럼 axios라는 프로미스 객체를 사용하는 함수를 이용해 특정 서버의 데이터를 뽑는 함수가 있습니다.
const getData = async () => {
try {
const result = await axios.get(
"https://b2ef45f8-e166-41d7-bd35-9ad159028fbf.mock.pstmn.io/test"
);
const products = result.data.products;
console.log(products);
console.log(`status:(${result.status}) 통신을 성공했습니다!`);
const data = JSON.stringify(products);
return data;
} catch (err) {
console.error(err);
console.log("결과를 가져오지 못했습니다.");
return err;
}
};
console.log(getData());
함수 내부에서는 값을 자유롭게 사용할 수 있지만 전역 컨텍스트에서 해당 함수로부터 값을 리턴하려면 Promise { } 이라는 값이 먼저 콘솔에 출력되고 위에 함수의 내용이 출력됩니다. 이는 프로미스가 비동기방식이어서 그렇다는건 이해하고 있습니다. 근데 이 프로미스 값(data변수)를 전역 컨텍스트에서 사용할 일이 있어서 전역 컨텍스트에서 사용하는 방법을 알고 싶습니다.
노드 14.8 이상이라면 파일 확장자를 .mjs
로 바꾸거나 package.json
의 type
을 module
로 바꾸고 console.log(await getData());
해보시면 되겠네요.
committed 10:52PM - 29 Jul 20 UTC
This unflags Top-Level await so it can be used by default in the module
goal. Th… is is accomplished by manually setting the
--harmony-top-level-await flag. We are allowing this as a one of
approval based on circumstances. It is not a precedent that future
harmony features will be manually enabled.
Refs: https://github.com/nodejs/node/issues/34551
PR-URL: https://github.com/nodejs/node/pull/34558
Reviewed-By: Mary Marchini <[email protected] >
Reviewed-By: Zeyu Yang <[email protected] >
Reviewed-By: Gus Caplan <[email protected] >
Reviewed-By: Matteo Collina <[email protected] >
Reviewed-By: Benjamin Gruenbaum <[email protected] >
Reviewed-By: Gireesh Punathil <[email protected] >
Reviewed-By: Shelley Vohr <[email protected] >
다른 사람들은 이런 질문을 했을 때 전부 불가능하다 말했습니다. 질문자님께서는 이런 사실을 어떻게 알고 계시는건가요? 답변 정말로 감사드립니다!!