如何在异步承诺调用上进行同步条件检查



场景:recommendationsArr是一个项目数组(它的 99.9% 不为空,但由于它是外部 api 调用,我更喜欢检查)。目的是为valueOnevalidItem和更新recommendationsArr提供值。
有效性取决于valueOne的存在,所以如果recommendationsArr[0]具有有效的valueOne那么我不需要获取数组其余部分的 api 结果。

const getContent = function (item) {
console.log("####### Inside the getContent function #########");
contentResponse = fetchContent(item);
return contentResponse;
}
if (recommendationsArr.length > 0) {
console.log("####### If Condition #########");
recommendationsArr.find((item) => {
getContent(item).then(function(response){
try { // to get valueOne
console.log("####### Try for: ######### ", term);
valueOne = response.content.valueOne; //may or may not be present
recommendationsArr.splice(recommendationsArr.indexOf(item), 1); // this is for styling first occurence is styled differently so thats popped out
validItem = item;
console.log("##### Valid item is: ", term);
return true;
} catch (err) {
console.log("##### Item not valid: ", recommendationsArr.indexOf(item));
valueOne = null;
return false;
}
});
});
console.log("######### Just hanging out!!! #########");
return {
component: <Layout><ComponentName
//pass other non-dependent props
validItem={validItem}
valueOne={valueOne}
recommendationsArr={recommendationsArr}
/></Layout>,
title: `Page Title`,
};
}
return null;

假设recommendationsArr = ["blue", "white", "green", "red"]; //usually the array is anywhere between 12-50 elements

发生了什么,控制台日志:

####### If Condition #########
####### getApiContent response for #########  blue
####### getApiContent response for #########  white
####### getApiContent response for #########  green
####### getApiContent response for #########  red
######### Just hanging out!!! #########
####### Try for: #########  blue
//I see data here
##### Valid item is:  blue
####### Try for: #########  white
//I see data here
##### Valid item is:  white
####### Try for: #########  green
//I see data here with valueOne missing in returned data
##### Item not valid: green
####### Try for: #########  red
//I see data here
##### Valid item is:  red

如您所见,API 请求getContent不断请求所有条款,然后 oly 进入.then。这会导致一大堆我什至不需要的 api 请求响应,我知道我正在尝试对 asyc.then的东西进行同步调用try/catch但我不知道如何实现这一点。

理想情况下,除非.then返回 false,否则不应调用tryAPI - 不再有 API 请求和退出。另外,我需要访问.then之外的response来更新组件的道具 我怎样才能做到这一点?我简要阅读了有关异步库的信息,这是否适合这种情况?

任何帮助/指导不胜感激。我一直被困在这个

在花了一些时间摆弄它之后,我认为最好不要尝试破解和使用异步库

我现在使用each Series方法一次运行一个异步操作,

var asyncEachSeries = require('async/eachSeries');
.        
.        
.
if (recommendationsArr.length > 0) {
asyncEachSeries(recommendationsArr, function (item, callback){
getContent(item).then(function(response){
try { 
//do stuff
return true;
} catch (err) {
//do stuff
}
return response;
});
});
}

最新更新