2017-10-19 10 views
0

약속 함수를 사용하여 XHR을 약속하고 있습니다. 응답을 얻는 방법을 알고 싶습니다. 그리고 응답이 성공하면 서버에 다시 게시하십시오. 이 성공 createChannel 경우약속 생성자를 사용하여 서버에 값을 다시 보내십시오.

나는 내가 hashvalue 변수를 가지고, 새로운 가치를 얻을 수있는 서버에 요청을 같은 것,이

function createChannel(method, url) { 
    return new Promise(function (resolve, reject) { 
     xhr.open(method, url, true); 
     xhr.setRequestHeader("Content-Type", "application/json"); 
    xhr.onload = function() { 
     if (xhr.readyState == 4) { 
      var hashValue = resolve(JSON.parse(xhr.responseText)); 
      console.log(hashValue); 
     } 
     else { 
      reject({ 
       status: this.status, 
       statusText: xhr.statusText 
      }); 
     } 
    }; 
    xhr.onerror = function() { 
      reject({ 
       status: this.status, 
       statusText: xhr.statusText 
      }); 
     }; 
    xhr.send(json); 
}); 
} 
createChannel(method, url) 
    .then(function (datums) { 
    console.log(datums) 
}).catch(function (err) { 
    console.error('Sorry There Was An Error!', err.statusText); 
}); 

같은 일을하고있다.

.then(function (createChannel) { 
    console.log(createChannel);  
}); 

약속을 사용하면 가능합니까? 조언 해 주셔서 감사합니다. 당신의 .then() 핸들러 내부

+0

그것은 분명 어떤 수단 "을 다시 보내"? 해결 된 약속을 얻고'.then() '핸들러에'datums' 값을 얻으면, 그 시점에서 당신은 무엇을하고 싶습니까? – jfriend00

+0

안녕하세요 @ jfriend00 wordings 내 선택에 대해 미안 해요, 내가 서버/URL에 내가 새로운 약속을 얻을 때 새로운 요청을하고 싶습니다. 해시 변수를 가져 와서 새로운 게시물 요청을 작성하려고합니다. – PythonRookie

+0

OK, 그 대답을 보여주었습니다. – jfriend00

답변

1

, 당신은 단지 새로운 요청을 발행하고 그 약속을 반환 처음으로 체인 :

createChannel(method, url).then(function (datums) { 
    console.log(datums); 
    // call some other async function here that returns a promise 
    return someOtherFunctionThatReturnsAPromise(datums); 
}).then(function(finalResult) { 
    console.log(finalResult);   
}).catch(function (err) { 
    console.error('Sorry There Was An Error!', err.statusText); 
}) 
+0

고마워,이게 내가 혼란스러워 졌다는 것 같아. 이걸 시험해보고 효과가 있는지 알아봐. – PythonRookie

+0

안녕하세요 @ jfriend00, 알고 싶습니다. createchannel이 이미 hashvalue 변수의 값을 보유하고 있습니까? 내가 이미 알아야 할 어리석은 질문을하는 경우 나는 모른다. 도움을 주셔서 감사합니다 – PythonRookie

+0

나는 그것을 알아 냈어, 고마워. – PythonRookie