【问题标题】:How do logical operators work with Promises in Javascript?逻辑运算符如何与 Javascript 中的 Promises 一起使用?
【发布时间】:2017-05-20 01:31:02
【问题描述】:

我正在关注关于 Promise 的教程,并遇到了以下使用逻辑运算符的 Promise,我不太明白。在下面的示例中,有一个函数 getJSON 返回一个承诺。它使用||(逻辑或??)运算符重复连接到未初始化的变量storyPromisestoryPromise = 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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 2020-09-03
      • 2011-09-23
      • 1970-01-01
      相关资源
      最近更新 更多