从 first 获取数据 .then 基于 second 的条件 .then

Get data from first .then based on condition on second .then

我按照上一个问题中的建议使用了 promises 从 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 对我来说应该是 return ['one', 'three'] 但实际上是 returning: [undefined, undefined, undefined].

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

您的回调是异步的,因此,除非您 'await' 使用 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);
  });

您在错误的阶段应用了 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);
});