逻辑运算符如何在Javascript中使用Promises?

时间:2017-05-20 01:31:03

标签: javascript logical-operators es6-promise

我正在学习有关promises的教程,并且遇到了使用逻辑运算符的promises,我无法理解。在下面的示例中,有一个函数getJSON返回一个promise。并且它使用storyPromise(逻辑OR ??)运算符重复连接到未初始化的变量||storyPromise = storyPromise || getJSON('story.json');)。我不确定OR带有promise的变量是什么意思,特别是在变量为undefined时的开头。

有人可以帮助解释相关生产线的逻辑/工作流程吗?承诺如何与布尔变量相互作用?

(我知道非常基本的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);
})

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);
}

1 个答案:

答案 0 :(得分:0)

这意味着如果定义了storypromise的值,则选择它,否则调用方法getjson()并分配从那里返回的值。 这也是许多其他语言的常见做法。 '或'的操作数可以是变量或方法。