【问题标题】:Get data from first .then based on condition on second .then根据第二个 .then 的条件从第一个 .then 获取数据
【发布时间】:2020-10-09 19:07:45
【问题描述】:

我按照上一个问题中的建议使用了 Promise 从 2 个异步调用中获取值。

但我希望根据第二次通话的条件获得第一次通话的结果。当我做我正在做的事情时,我总是变得不确定。如何获得我想要的结果。

第一个 JSON:

let first_json = [
    {
        "company": "one"
    },
    {
        "company": "two"
    },
    {
        "company": "three"
    }
]

第二个 JSON 依赖于第一个,格式相似。

使用我所做的承诺:

$.getJSON(first_json)
 .then(first_data =>
      first_data.map(d => {
          return d.company;
      })
  )
 .then(promises => Promise.all(promises))
 .then(company => company.map(c => {
        let second_json = json_string + c;
        $.getJSON(second_json, function(data) {
            if (data.length > 0) return c;
        });
    }))
 .then(arr => {
     console.log(arr);
  });

arr 对我来说应该返回 ['one', 'three'] 但实际上是返回: [undefined, undefined, undefined].

为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • 您没有从 company.map(...) 回调中返回值。因此,您将company 数组映射到undefined 值数组。不太确定$.getJSON 是否会返回一个类似promise 的对象。
  • @FelixKling,对不起,我对承诺很陌生。你能扩展一下吗?

标签: javascript jquery json ecmascript-6 es6-promise


【解决方案1】:

您的回调是异步的,因此,除非您使用 then“等待”它,否则您将无法立即使用它,因此您无法根据它采取行动。

相反,这样做:

$.getJSON(first_json)
  .then(first_data =>
    first_data.map(d => {
      return d.company;
    })
  )
  .then(promises => Promise.all(promises))
  .then(company => company.map(c => {
    let second_json = json_string + c;
    return $.getJSON(second_json)
      .then(data => {
        if (data.length > 0) return c;
      });
  }))
  .then(promises => Promise.all(promises))
  .then(arr => {
    console.log(arr);
  });

【讨论】:

    【解决方案2】:

    您在错误的阶段应用Promise.all

    $.getJSON(first_json).then(first_data => {
        const companies = first_data.map(d => {
            return d.company;
        });
        const promises = companies.map(c => {
    //        ^^^^^^^^
            let second_json = json_string + c;
            return $.getJSON(second_json).then(data => {
    //      ^^^^^^
                if (data.length > 0) return c;
            });
        });
        return Promise.all(promises);
    //         ^^^^^^^^^^^
    }).then(arr => {
        console.log(arr);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多