场景:recommendationsArr
是一个项目数组(其99.9%不为空,但由于它是外部api调用,我更喜欢检查)。目的是为valueOne
,validItem
和更新的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 try/catch
进行同步调用.then
,但我不知道如何实现这一点。 / p>
理想情况下,除非.then
返回false,否则不应调用API,如果try
返回true,则不再需要API请求并退出。另外,我需要访问response
之外的.then
来更新组件的道具我该如何实现?我简要介绍了async library,是否适合这种情况?
感谢任何帮助/指导..我一直坚持这个
答案 0 :(得分:0)