在Javascript中,逻辑运算符如何处理承诺?
我正在学习一个关于允诺的教程,遇到了下面的允诺与逻辑运算符的用法,我不太理解。在下面的示例中,有一个函数在Javascript中,逻辑运算符如何处理承诺?,javascript,logical-operators,es6-promise,Javascript,Logical Operators,Es6 Promise,我正在学习一个关于允诺的教程,遇到了下面的允诺与逻辑运算符的用法,我不太理解。在下面的示例中,有一个函数getJSON返回承诺。并且它使用| |(逻辑OR??)运算符反复连接到未初始化的变量storyPromise(storyPromise=storyPromise | | getJSON('story.json');)。我不太清楚或一个有承诺的变量意味着什么,尤其是在变量未定义时 有人能帮我解释一下相关生产线的逻辑/工作流程吗?承诺如何与布尔变量相互作用 (我知道非常基本的Javascript
getJSON
返回承诺。并且它使用| |
(逻辑OR??)运算符反复连接到未初始化的变量storyPromise
(storyPromise=storyPromise | | getJSON('story.json');
)。我不太清楚或
一个有承诺的变量意味着什么,尤其是在变量未定义时
有人能帮我解释一下相关生产线的逻辑/工作流程吗?承诺如何与布尔变量相互作用
(我知道非常基本的Javascript,但不知道承诺等现代功能)
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);
}
这意味着,如果定义了storypromise,则选择它的值,然后调用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);
}