根据第二个条件从第一个条件获取数据

时间:2020-06-19 13:52:13

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

我按照上一个问题中的建议使用了promise,以从两个异步调用中获取值。

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

第一个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]

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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