2017-05-20 6 views
0

약속에 대한 지침서를 읽고 다음과 같은 논리적 연산자 사용 약속이 있습니다. 이해할 수는 없습니다. 아래 예제에는 약속을 반환하는 함수 getJSON이 있습니다. 그리고 초기화되지 않은 변수 || (논리 OR ??) 연산자 (storyPromise = storyPromise || getJSON('story.json');)를 반복적으로 사용하여 초기화되지 않은 변수에 연결됩니다. 나는 정확히 무엇이 변수 undefined 일 때 특히 처음에는 OR에 무엇을 의미하는지 확신 할 수 없다.논리 연산자는 Javascript의 약속과 어떻게 작동합니까?

문제의 라인에 대한 논리/작업 흐름을 설명해 줄 사람이 있습니까? 약속은 부울 변수와 어떻게 상호 작용합니까? 다음과 같이

getJSON() 함수가 정의

var storyPromise; 

function getChapter(i) { 
    storyPromise = storyPromise || getJSON('story.json'); 

    return storyPromise.then(function(story) { 
    return getJSON(story.chapterUrls[i]); 
    }) 
} 

// and using it is simple: 
getChapter(0).then(function(chapter) { 
    console.log(chapter); 
    return getChapter(1); 
}).then(function(chapter) { 
    console.log(chapter); 
}) 

(I는 약속과 같은 매우 기본적인 자바 스크립트가 아니라 현대적인 기능을 알고) :

function get(url) { 
    // Return a new promise. 
    return new Promise(function(resolve, reject) { 
    // Do the usual XHR stuff 
    var req = new XMLHttpRequest(); 
    req.open('GET', url); 

    req.onload = function() { 
     // This is called even on 404 etc 
     // so check the status 
     if (req.status == 200) { 
     // Resolve the promise with the response text 
     resolve(req.response); 
     } 
     else { 
     // Otherwise reject with the status text 
     // which will hopefully be a meaningful error 
     reject(Error(req.statusText)); 
     } 
    }; 

    // Handle network errors 
    req.onerror = function() { 
     reject(Error("Network Error")); 
    }; 

    // Make the request 
    req.send(); 
    }); 
} 

function getJSON(url) { 
    return get(url).then(JSON.parse); 
} 

답변

0

이 그 storypromise의 값을 선택 뜻이있는 경우 그렇지 않으면 getjson() 메서드를 호출하고 거기에서 반환 된 값을 할당합니다. 이것은 많은 다른 언어에서도 일반적인 관행입니다. '또는'의 피연산자는 변수 또는 메서드가 될 수 있습니다.