2017-09-17 3 views
0
export function getHotOffers() { 
    let offers; 
    getRequest('/hot-offers').then(x => offers = x); 
    alert(offers); 
    return JSON.parse(offers); 
} 

그건 내 내보내기 기능입니다. 서버에 비동기 적으로 요청하고 JSON 문자열을 가져옵니다. 프로젝트를 디버깅 할 때 모든 것이 작동하고 경고가 문자열을 반환하지만 코드를 실행하면 경고는 정의되지 않은 상태로 반환됩니다. 이 문제를 어떻게 해결할 수 있습니까?약속 완료 결과가 정의되지 않았습니다.

답변

1

데이터가 동 기적으로 사용 가능하지 않습니다. 쿠폰에 액세스하려면 약속을 사용해야합니다. 마찬가지로

export function getHotOffers() { 
    let offerPromise = getRequest('/hot-offers') 
     .then(offers => JSON.parse(offers)); 
    return offerPromise; 
} 

,이 약속을 받고있을 것입니다 호출하고 마지막 값을 얻기 위해 .then 방법을 사용해야합니다 코드.

getHotOffers().then(offers => { 
    alert(offers); 
}); 
2

이것은 약속의 작동 방식이 아닙니다. getRequest() 이후의 코드는 약속 완료를 기다리지 않고 바로 실행됩니다.

export function getHotOffers() { 
    let offers; 
    getRequest('/hot-offers').then(x => 
     //this only happens after the request is done 
     offers = x 
    ); 
    //this code runs right away, before the request completes 
    alert(offers); 
    //so does this, so "offers" will be undefined at this point 
    return JSON.parse(offers); 
} 

모든 코드는 다음과 같이 다시 전화 내부에 있어야 요청을 반환 한 후 실행합니다 : then에 전달 된 콜백 전에

export function getHotOffers() { 
    return getRequest('/hot-offers'); 
} 

//somewhere else 
getHotOffers().then(offers => { 
    useTheOffers(offers); 
}); 
1

귀하의 코드 진행이라고합니다. async/await 사용

, 당신은이 문제를 회피하고, 코드의 가독성을 향상시킬 수

// emulate your "getRequest" function which returns a promise: 
 
async function getRequest(path) { 
 
    await new Promise(resolve => setTimeout(resolve, 500)); // simulate response delay 
 
    const offers = ['hot-offer-1', 'hot-offer-2', 'hot-offer-3']; 
 
    return offers; 
 
} 
 

 
async function getHotOffers() { 
 
    const offers = await getRequest('/hot-offers'); 
 
    console.log(offers); 
 
    return JSON.parse(offers); 
 
} 
 

 
getHotOffers();

관련 문제