【问题标题】:How to pass parametr to .then in Promise technology如何在 Promise 技术中将参数传递给 .then
【发布时间】:2018-06-05 22:30:40
【问题描述】:

我尝试在 Promise 链中将参数传递给 .then。我找到了这个主题Promises, pass additional parameters to then chain,但我对 JS/Promise 很陌生,无法将其与我的示例相匹配。

componentDidMount() {

    function getData(url) {
      return new Promise(function(resolve, reject) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", url, true);
        xhttp.onload = function() {
          if (xhttp.status === 200) {
            resolve(JSON.parse(xhttp.response));
          } else {
            reject(xhttp.statusText);
          }
        };
        xhttp.onerror = function() {
          reject(xhttp.statusText);
        };
        xhttp.send();
      });
    }

    function getHeaders(url) {
      return new Promise(function(resolve, reject) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", url, true);
        xhttp.onload = function() {
          if (xhttp.status === 200) {
            resolve(getPagesNumber(xhttp.getResponseHeader("Link")));
          } else {
            reject(xhttp.statusText);
          }
        };
        xhttp.onerror = function() {
          reject(xhttp.statusText);
        };
        xhttp.send();
      });
    }

    var promise = getData("https://api.github.com/orgs/angular/members");
    promise.then(function(members) {
      console.log(members);
      return getHeaders("https://api.github.com/repos/angular/angular-jquery-ui/contributors")
    })
    .then(function(pgItr) {
      console.log(pgItr);
    })
    .catch(function(error){
      console.log(error);
    });

  }

我需要从

传递 url

return getHeaders("https://api.github.com/repos/angular/angular-jquery-ui/contributors")

到 .then(console.log(pgItr);)

我想在 componentDidMount() { 之后添加一个变量,并在第一个 .then 中设置这个变量(带有 url),然后在第二个 .then 中读取它。但我认为这很棘手/作弊/不正确的解决方案。

【问题讨论】:

  • 字符串"https://api.github.com/repos/angular/angular-jquery-ui/contributors" 似乎是一个常数。为什么需要传递它?为什么不直接在与var promise 相同的范围内声明一个常量变量?
  • 因为 url 是动态生成的,所以我得到它有多少子页面并将这个数字传递给 next .then 但我也需要一个 url:url-subpages 关系。
  • 嗯,这不是您发布的代码中发生的情况。请edit你的问题
  • 目前尚不完全清楚您要寻求什么帮助,但也许其中一种技术会有所帮助:How to chain and share prior results with Promises
  • 嗨,我是 Stack 新手,我有一个问题:我在问题中输入了错误的代码。我应该怎么做:a) 删除问题并再次提问或 b) 更改此问题中的代码或 c) 添加新的类似问题?

标签: javascript es6-promise


【解决方案1】:

您始终可以使用Promise.allthen 返回多个承诺或值,如下所示:

const somePromise = Promise.resolve("some value");
somePromise
    .then(someValue => Promise.all([someValue, Promise.resolve("other value")]))
    .then(([someValue, otherValue]) => console.log(`[${someValue}] and [${otherValue}]`));

【讨论】:

    猜你喜欢
    • 2014-07-13
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 2020-06-13
    • 2020-12-14
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多