JSON.parse()
JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성.
즉, 아래와 같이 string 형식을 본래 객체로 변환해줄 수 있다.
출처 MDN
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
const readAllUsers = () => {
// TODO: Promise.all을 이용해 작성합니다
return Promise.all([getDataFromFilePromise(user1Path),
getDataFromFilePromise(user2Path)])
.then((data) => {
return JSON.parse(data);
})
}
여기서 getDataFromFilePromise(user1Path)를 통해 도출된 값은 객체의 string 타입이다.
따라서, Promise.all의 결과로 도출되어 then((data))에 들어가는 값은
['{객체 모양 무엇}', '{객체 모양 무엇}']
이러한 형식이었을 것이다. 이 상태에서 최종적으로 JSON.parse 를 사용했으나, 이미 배열상태이므로 'Unexpected token' 에러가 도출되었다.
그렇다면 Promise.all() 전달인자에 JSON.parse를 씌워서 객체 형태로 넣는 방법은 어떨까?
[{객체 모양 무엇}, {객체 모양 무엇}]
이렇게 잘 들어가지 않을까?
const readAllUsers = () => {
// TODO: Promise.all을 이용해 작성합니다
return Promise.all([JSON.parse(getDataFromFilePromise(user1Path)),
JSON.parse(getDataFromFilePromise(user2Path))])
.then((data) => {
return data;
})
}
생각을 그대로 옮겨보았고, 이번에도 역시나 'Unexpected token' 에러..
이번에는 왜 안되는 걸까? -> to be continue..
올바른 접근
const readAllUsers = () => {
// TODO: Promise.all을 이용해 작성합니다
return Promise.all([getDataFromFilePromise(user1Path),
getDataFromFilePromise(user2Path)])
.then(([data1, data2]) => {
return JSON.parse(`[${data1}, ${data2}]`);
})
}
Promise.all을 통해 실제로 전달되는 인자의 형태에 맞게 then의 파라미터를 만들어준다.
[data1, data2] -> 여기서 백틱사용하여 문자열로 표현 후 JSON.parse 처리!