根据第二个 .then 上的条件从第一个 .then 获取数据



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

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

第一个 JSON:

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

第二个 JSON 依赖于第一个 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].

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

你的回调是异步的,所以,除非你用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);
});

最新更新