简体   繁体   English

如何对异步Promise调用进行同步条件检查

[英]How to do sync conditional check on async promise call

Scenario: recommendationsArr is an array of items (Its 99.9% not null, but since its an external api call I prefer to have a check). 场景: recommendationsArr是一个项目数组(它的99.9%不为null,但是由于它是一个外部api调用,所以我希望进行检查)。 The purpose is to have values for valueOne , validItem , and an updated recommendationsArr . 其目的是让值valueOnevalidItem ,和更新recommendationsArr
The validity depends on the existence of valueOne , so if the recommendationsArr[0] has valid valueOne then I don't need to fetch api results for the rest of the array. 有效性取决于valueOne的存在,因此,如果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;

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

What is happening, console log: 发生了什么,控制台日志:

####### 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

As you see, the API request getContent keeps requesting for all terms, and oly then gets to .then . 如您所见,API请求getContent继续请求所有条款,然后oly进入.then This causes a whole bunch of api requests-response that I wont even need, I know am trying to make synchronize calls try/catch on something that's asyc .then but I don't know how to achieve this. 这会导致一大堆我什至不需要的api请求-响应,我知道我正在try/catch对asyc进行同步调用try/catch 。然后.then但我不知道该如何实现。

Ideally, API should not be called unless .then returns false, if try returns true - no more API requests and exit. 理想情况下,不应调用API,除非.then返回false,如果try返回true,则不再有API请求并退出。 Also, I would need to access the response outside of .then to update component's props How can I achieve this? 另外,我需要访问.then之外的response以更新组件的道具。如何实现此目的? I briefly read about the async library , is that suitable for this situation? 我简要介绍了异步库 ,它适合这种情况吗?

Any help/guidance is appreciated.. I've been stuck with this 任何帮助/指导表示赞赏。.

After spending some time fiddling around with it, I figured its probably best to not try and hack and use async-library 在花了一些时间摆弄它之后,我发现可能最好不要尝试破解和使用异步库

I am now using a eachSeries method to run a single async operation at a time, 我现在正在使用eachSeries方法一次运行一个异步操作,

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;
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM