2017-10-02 1 views
-3

이 문제를 해결할 방법을 찾고 있었고 검색 기술이 동등하지 않은 경우 사과드립니다.ES6 호출 기능 가져 오기

내 문제 : API를 가져 오는 중이고 모든 데이터가 완전히로드되었는지 알고 싶습니다. 문서를 읽으면, 내가 가져올 수있는 문장을 연결할 수있는 것처럼 보입니다. 그러나, 그들은 마치 모두가 이전에 기다리지 않고 동시에 발사되는 것처럼 보입니다. 여기

내 코드입니다 :

fetch(myUrl, { 
    method: 'post', 
    headers: { 
     'Content-Type': 'application/json; charset=utf-8',    
    }, 
    credentials: 'include',   
    body: data 
    })         
     .then(fetchStatus) 
     .then(json) 
     .then(function(msg){          
      showSearchResults(); 
      setTimeout(function(){ console.log("Next then should fire after this"); }, 4000);         
     }) 
     .then(function(){ 
      return console.log("The 2nd is firing!");         
     }); 

function fetchStatus(response) { 
    if (response.status >= 200 && response.status < 300) { 
     return Promise.resolve(response) 
    } else { 
     return Promise.reject(new Error(response.statusText)) 
    } 
} 

function json(response) { 
    return response.json() 
} 

가 비동기 경우에 매우 중요하지만,이 사건으로 인해 내가 이전에 의해 생성되는 콘텐츠와 함께 작동하도록 노력하고 있다는 사실을 동기화 할 필요가 전화, showSearchResults();

도움을 주시면 감사하겠습니다.

+0

당신이 {>는 'MSG =에 대해 잊지 마세요 ES6를 사용하는 경우 ... }'함수 표기법. 그것은 많은 장황함을 줄여 줄 수 있고'var self = this'의 춤을 피할 수 있습니다. – tadman

+0

Promise.all에서'showSearchResults'를 래핑하여 해결할 때까지 기다리십시오. – maioman

+0

여기에 어떤 문제가 있는지 명확하지 않습니다. 당신은 하나의'fetch' 호출을 가지고 있으며, 그 체인 내의 각 핸들러는 이전의 것이 실행 된 후에 만 ​​실행될 것입니다. 정확히 뭐가 문제 야? (또한 : showSearchResults에 어떤 종류의 인수를 제공해서는 안됩니까?) –

답변

0

. 위의 예에서 showSearchResults 뒤에 두 번째 console.log을 실행하려면 return showSearchResults()을 연결하고 .then을 연결해야합니다 (이는 showSearchResults이 약속을 반환하는 경우에만 작동하며 그렇지 않은 경우에는 비슷한 것으로 포장해야합니다. 당신은 fetchStatus에 대해 가지고있는 방법). 당신이 setTimeout 떨어져 체인입니다 .then 원한다면

마찬가지로, 당신과 같이 쓸 수있다 :

fetch(url, { method: 'post', etc... }) 
    .then(fetchStatus) 
    .then(json) 
    .then(function(msg){ 
     return new Promise(function(resolve, reject){ 
     setTimeout(function() { 
      console.log("Next then fires after promise resolves"); 
      resolve(); 
     }, 4000) 
     }) 
    }) 
    .then(function(){ 
     console.log("Second is firing") 
    }) 
    .catch(err => console.log(error)) // always remember to catch errors! 
+0

정확하게 작동하기를 바랐던 것처럼 작동합니다. 게시하기 전에이 방법을 시도했지만 약속에 "새로운"키워드가 없어 잠시 동안 고민했습니다. 도와 줘서 고마워! – zadees

-1

then 함수에 대한 후속 호출은 첫 번째 호출 인 동일한 약속에 대한 콜백 체인을 나타냅니다. 그것들은 다른 모든 약속을 나타내는 것이 아니며 그렇게 빠른 속도로 실행됩니다. 당신이 대신해야 할 것은 다음과 같이 콜백 함수 내에서 체인 그들이다하십시오 .then가 이전 .then 호출에서 약속을 반환하지 않는 한 그 코드가 순차적으로 실행됩니다 보장하지 않습니다 체인 연결

fetch(myUrl, { 
    method: 'post', 
    headers: { 
    'Content-Type': 'application/json; charset=utf-8', 
    }, 
    credentials: 'include', 
    body: data 
    } 
).then((response) => { 
    // fetch promise is resolved 
    fetchStatus(response).then((response) => { 
     // fetchStatus promise is resolved 
     json(response).then((msg) => { 
      // json promise is resolved 
      showSearchResults(); 
      setTimeout(function(){ 
       console.log("Next then should fire after this"); 
      }, 4000); 
      // note that this log will execute before the previous one because 
      // `setTimeout` does not return a promise 
      console.log("The 2nd is firing!"); 
     }); 
    }); 
}); 

function fetchStatus(response) { 
    if (response.status >= 200 && response.status < 300) { 
     return Promise.resolve(response) 
    } else { 
     return Promise.reject(new Error(response.statusText)) 
    } 
} 

function json(response) { 
    return response.json() 
}