私は約束のチュートリアルに従っており、以下の論理演算子との約束の使用に遭遇しています。下の例では、約束を返す関数getJSON
があります。また、の初期化されていない変数||
(論理OR?)演算子を繰り返し使用して(storyPromise = storyPromise || getJSON('story.json');
)接続されています。私は確かに、が何を意味するのか、特に変数がundefined
であるときに、約束のある変数を確かめるのではない。論理演算子は約束事とJavascriptでどのように動作しますか?
問題の行のロジック/ワークフローについて説明できる人がいますか?約束はブール変数とどのように相互作用しますか?
次のようにgetJSON()
関数が定義されている(私はそのような約束など現代的な機能は非常に基本的なJavascriptを知っているがない)
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);
})
:
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);
}