const path = require("path");
const { getDataFromFilePromise } = require("./02_promiseConstructor");
const user1Path = path.join(__dirname, "files/user1.json"); /// 문자열
const user2Path = path.join(__dirname, "files/user2.json");
[
{
"name": "김코딩",
"age": 26,
"sex": "Male",
"company": {
"name": "코드스테이츠"
}
}, -> string -> JSON.parse ->
{
"name": "박해커",
"age": 40,
"sex": "Female",
"company": {
"name": "Anomymous"
}
}
]
? 에러가 난다면 1번째것만 객체화 시키다가 error가나면 객체가 배열안에 들어가지 않는다.
? 실패하면 catch, catch는 인자값으로 함수를 받는다.
Promise.all([p1, p2, p3])
.then(values => { console.log(values)
}); [3, 1337, "foo"]
Promise.all
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
const readAllUsers = () => {
// TODO: Promise.all을 이용해 작성합니다
const promise1 = getDataFromFilePromise(user1Path).then((string) =>
JSON.parse(string)
); /// user1.json 을 객체화
const promise2 = getDataFromFilePromise(user2Path).then((string) =>
JSON.parse(string)
); /// user2.json 을 객체화
return Promise.all([promise1, promise2]).catch((error) => {
console.log(error);
});
};
async func() {}; 선언식
const func = async function() {}; 표현식
const func = async () => {}; 표현식 애로우
async가 계속 비동기 await가 checkpoint며 순차적으로 실행된다.
성공여부에 따라서 비동기 작동이 된다.
비동기 async 동기 sync 동기가 순차적으로 비동기는 병렬적.
await가 끝날때까지 1번이 무조건 들어간다.
순서를 진행하기 위해서 async로 만들었고 await는 순서를 만든다.
const readAllUsersAsyncAwait = async () => {
// TODO: async/await 키워드를 이용해 작성합니다
return [
await getDataFromFilePromise(user1Path).then((string) =>
JSON.parse(string)
), /// user1.json 을 객체화
await getDataFromFilePromise(user2Path).then((string) =>
JSON.parse(string)
), /// user2.json 을 객체화
];
};
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/await
const readAllUsersAsyncAwait = async () => {
try{
return [
await getDataFromFilePromise(user1Path).then((string) =>
JSON.parse(string)
), /// user1.json 을 객체화
await getDataFromFilePromise(user2Path).then((string) =>
JSON.parse(string)
), /// user2.json 을 객체화
]} catch(error) {
console.log(error)
};
};
https://www.youtube.com/watch?v=cuEtnrL9-H0
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
https://developer.mozilla.org/ko/docs/Web/API/Body/json