2017-12-23 1 views
2

배열 인 두 개의 파일이 있는데 가져 오기에서로드하려고합니다. 가져 오기 내가이 FO 반환에 변수를 할당가져 오기에서 변수 할당 약속 약속

async function getData(file) { 
    const data = await fetch(`./assets/resources/${file}.json`); 
    return await data.json() 
} 
여기에

입니다 : 내가 파일을 가져 비동기 기능이

let notes = getData("notes").then(res => res) 
let pentagrama = getData("pentagrama").then(res => res) 

를하지만 이것으로 내가 가진 전부입니다 from google chrome console

어떻게 실제로 값을 얻을 수 있습니까?

+0

* 비동기 호출에서 응답을 반환하는 방법 *을보실 수 있습니다. * –

+0

고맙습니다. 처음으로 데이터를로드하고 나중에 사용해야하는 것은 처음입니다. 왜 이런 일이 있었는지 혼란 스러웠습니다 –

답변

3

getData의 결과는 항상 데이터로 해석되는 Promise입니다. 값에 액세스하려면 async/await 사용할 수 있습니다

(async() => { 

    let notes = await getData("notes"); 
    let pentagrama = await getData("pentagrama"); 

    // use them here 

})(); 

또는 둘 다 약속 해결하기 위해 기다릴 Promise.all을 사용할 수 있으며, 수신 된 데이터에 액세스 :

let notesP = getData("notes"); 
let pentagramaP = getData("pentagrama"); 

Promise.all([noteP, pentagramaP]).then(res => { 

    let notes = res[0]; 
    let pentagrama = res[1]; 

    // use them here 

}); 
+0

감사합니다. 두 가지 모두 저에게 도움이되었습니다. 변수의 실제 값이 될 반환 값으로 .then 메서드를 사용할 때 기대하고있었습니다. –

0

ASYNC

AWAIT

요령에 응답을 확인하려면이 방법이 유용 할 것입니다. 왜냐하면 콘솔에서 실행되는 모든 것이 기본적으로 비동기 함수 (단순한 추측)로 래핑되기 때문에 비동기 함수없이 기다릴 수 있기 때문입니다.

만 해당 콘솔에서 작동 :

const getData = (file) => (
    fetch(`./assets/resources/${file}.json`).then(data => data.json()); 
) 

let notes = await getData("notes") 
let pentagrama = await getData("pentagrama") 

을하지만 당신은 응용 프로그램에서이 작업을 얻으려면, 당신은 항상 기다리고 포장해야한다는 것을 기억 비동기 내부

신청서 작성 방법 :

const getData = async (file) => (
    await fetch(`./assets/resources/${file}.json`).then(data => data.json()); 
) 

const wrapperFunc = async() => { 
    let notes = await getData("notes") 
    let pentagrama = await getData("pentagrama") 
} 
+0

오, 정말 고마워, 미래에 대해 알고 좋은이 정보를 몰랐다. –