【发布时间】:2017-05-20 01:31:02
【问题描述】:
我正在关注关于 Promise 的教程,并遇到了以下使用逻辑运算符的 Promise,我不太明白。在下面的示例中,有一个函数 getJSON 返回一个承诺。它使用||(逻辑或??)运算符重复连接到未初始化的变量storyPromise(storyPromise = storyPromise || getJSON('story.json');)。我不确定OR 一个带有承诺的变量是什么意思,尤其是在变量为undefined 的开头。
有人可以帮助解释相关线路的逻辑/工作流程吗? Promise 如何与布尔变量相互作用?
(我知道非常基本的 Javascript,但不知道诸如 Promise 之类的现代功能)
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);
})
getJSON()函数定义如下:
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);
}
【问题讨论】:
标签: javascript logical-operators es6-promise