-3

I am trying to call an asyncronous function from a syncronous function. The asyncronous function getMLRiskScore returns an api response which i need to dispay when another function evaluateMLRiskCategory . Unfortunately i keep getting [object Promise] Whats the best way to retrieve the ml score , the my result log shows the value expected

export async function getMLRiskScore(params: any): Promise<any | null> {

    var mlScoringRequestPayload = {
        modelConfigs: { modelId: 'hts_xgb_1211_jan_2023', encounterDate: '2023-03-15', facilityId: '', debug: 'true' },
        variableValues: {
          Age: 17,
          births: 0,
          pregnancies: 0,
          literacy: 0,
          poverty: 0,
          anc: 0,
          pnc: 0,
          sba: 0,
          hiv_prev: 0,
          hiv_count: 0,
          condom: 0,
          intercourse: 0,
          in_union: 0,
          circumcision: 0,
          partner_away: 0,
          partner_men: 0,
          partner_women: 0,
          sti: 0,
          fb: 0,
          PopulationTypeGP: 1,
          PopulationTypeKP: 0,
          PopulationTypePRIORITY: 0,
          KeyPopulationFSW: 0,
          KeyPopulationMSM: 0,
          KeyPopulationNR: 1,
          KeyPopulationOther: 0,
          KeyPopulationPWID: 0,
          PriorityPopulationAGYW: 0,
          PriorityPopulationFISHERMEN: 0,
          PriorityPopulationNR: 1,
          PriorityPopulationOTHER: 0,
          DepartmentEMERGENCY: 0,
          DepartmentIPD: 1,
          DepartmentOPD: 0,
          DepartmentPMTCT: 0,
          DepartmentVCT: 0,
          IsHealthWorkerNO: 0,
          IsHealthWorkerNR: 1,
          IsHealthWorkerYES: 0,
          SexuallyActiveNO: 0,
          SexuallyActiveNR: 1,
          SexuallyActiveYES: 0,
          NewPartnerNO: 0,
          NewPartnerNR: 1,
          NewPartnerYES: 0,
          PartnerHIVStatusNEGATIVE: 0,
          PartnerHIVStatusNR: 1,
          PartnerHIVStatusPOSITIVE: 0,
          PartnerHIVStatusUNKNOWN: 0,
          NumberOfPartnersMULTIPLE: 0,
          NumberOfPartnersNR: 1,
          NumberOfPartnersSINGLE: 0,
          AlcoholSexALWAYS: 0,
          AlcoholSexNEVER: 0,
          AlcoholSexNR: 1,
          AlcoholSexSOMETIMES: 0,
          MoneySexNO: 0,
          MoneySexNR: 1,
          MoneySexYES: 0,
          CondomBurstNO: 0,
          CondomBurstNR: 1,
          CondomBurstYES: 0,
          UnknownStatusPartnerNO: 0,
          UnknownStatusPartnerNR: 1,
          UnknownStatusPartnerYES: 0,
          KnownStatusPartnerNO: 0,
          KnownStatusPartnerNR: 1,
          KnownStatusPartnerYES: 0,
          PregnantNO: 0,
          PregnantNR: 1,
          PregnantYES: 0,
          BreastfeedingMotherNO: 0,
          BreastfeedingMotherNR: 1,
          BreastfeedingMotherYES: 0,
          ExperiencedGBVNO: 0,
          ExperiencedGBVYES: 0,
          CurrentlyOnPrepNO: 0,
          CurrentlyOnPrepNR: 0,
          CurrentlyOnPrepYES: 0,
          CurrentlyHasSTINO: 0,
          CurrentlyHasSTINR: 0,
          CurrentlyHasSTIYES: 0,
          SharedNeedleNO: 0,
          SharedNeedleNR: 1,
          SharedNeedleYES: 0,
          NeedleStickInjuriesNO: 0,
          NeedleStickInjuriesNR: 1,
          NeedleStickInjuriesYES: 0,
          TraditionalProceduresNO: 0,
          TraditionalProceduresNR: 1,
          TraditionalProceduresYES: 0,
          MothersStatusNEGATIVE: 0,
          MothersStatusNR: 1,
          MothersStatusPOSITIVE: 0,
          MothersStatusUNKNOWN: 0,
          ReferredForTestingNO: 0,
          ReferredForTestingYES: 0,
          GenderFEMALE: 1,
          GenderMALE: 0,
          MaritalStatusDIVORCED: 0,
          MaritalStatusMARRIED: 0,
          MaritalStatusMINOR: 0,
          MaritalStatusPOLYGAMOUS: 1,
          MaritalStatusSINGLE: 0,
          EverTestedForHivNO: 0,
          EverTestedForHivYES: 1,
          MonthsSinceLastTestLASTSIXMONTHS: 0,
          MonthsSinceLastTestMORETHANTWOYEARS: 1,
          MonthsSinceLastTestNR: 0,
          MonthsSinceLastTestONETOTWOYEARS: 0,
          MonthsSinceLastTestSEVENTOTWELVE: 0,
          ClientTestedAsCOUPLE: 0,
          ClientTestedAsINDIVIDUAL: 0,
          EntryPointIPD: 0,
          EntryPointOPD: 0,
          EntryPointOTHER: 0,
          EntryPointPEDIATRIC: 0,
          EntryPointPMTCT_ANC: 0,
          EntryPointPMTCT_MAT_PNC: 0,
          EntryPointTB: 0,
          EntryPointVCT: 1,
          EntryPointVMMC: 0,
          TestStrategyHB: 0,
          TestStrategyHP: 0,
          TestStrategyINDEX: 0,
          TestStrategyMO: 0,
          TestStrategyNP: 0,
          TestStrategyOTHER: 0,
          TestStrategySNS: 0,
          TestStrategyVI: 0,
          TestStrategyVS: 1,
          TbScreeningCONFIRMEDTB: 0,
          TbScreeningNOPRESUMEDTB: 0,
          TbScreeningPRESUMEDTB: 0,
          ClientSelfTestedNO: 1,
          ClientSelfTestedYES: 0,
          CoupleDiscordantNO: 0,
          CoupleDiscordantNR: 1,
          CoupleDiscordantYES: 0,
          SEXUALNO: 0,
          SEXUALYES: 1,
          SOCIALNO: 1,
          SOCIALYES: 0,
          NONENO: 1,
          NONEYES: 0,
          NEEDLE_SHARINGNO: 1,
          NEEDLE_SHARINGYES: 0,
          ReceivedPrEPNO: 1,
          ReceivedPrEPYES: 0,
          ReceivedPEPNO: 1,
          ReceivedPEPYES: 0,
          ReceivedTBNO: 1,
          ReceivedTBYES: 0,
          ReceivedSTINO: 1,
          ReceivedSTIYES: 0,
          GBVSexualNO: 1,
          GBVSexualYES: 0,
          GBVPhysicalNO: 1,
          GBVPhysicalYES: 0,
          GBVEmotionalNO: 1,
          GBVEmotionalYES: 0,
          dayofweekFRIDAY: 0,
          dayofweekMONDAY: 0,
          dayofweekSATURDAY: 0,
          dayofweekSUNDAY: 0,
          dayofweekTHURSDAY: 0,
          dayofweekTUESDAY: 0,
          dayofweekWEDNESDAY: 1,
        },
      };
    
      const url = 'http://197.248.44.228:8600/openmrs/ws/rest/v1/keml/casefindingscore';
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        },
        body: JSON.stringify(mlScoringRequestPayload),
      });

      return response.json().then(result => {
        if (result?.result?.predictions) {
          console.log("---y", result?.result?.predictions)
          const lowRiskThreshold = 0.002625179;
          const mediumRiskThreshold = 0.010638781;
          const highRiskThreshold = 0.028924102;
          if (result?.result?.predictions['probability(1)'] > highRiskThreshold) {
            return 'Client has a very high probability of a HIV positive test result. Testing is strongly recommended';
          }
          if (
            result?.result?.predictions['probability(1)'] < highRiskThreshold &&
            result.result.predictions['probability(1)'] > mediumRiskThreshold
          ) {
            return 'Client has a high probability of a HIV positive test result. Testing is strongly recommended';
          }
          if (result?.result?.predictions['probability(1)'] > lowRiskThreshold) {
            return 'Client has a medium probability of a HIV positive test result. Testing is recommended';
          }
          if (result?.result?.predictions['probability(1)'] <= lowRiskThreshold) {
            return 'Client has a low probability of a HIV positive test result. Testing may not be recommended';
          } else {
            return `No results found`;
          }
        } else {
          return `No results found`;
        }
      });

}

This is my syncronous function :

evaluateMLRiskCategory(...args) {
    return getMLRiskScore(args).then(result => {
        console.log('-----my result', result); // this shows the expected value
        return result;
      })
      .catch(err => {
        return `An error occured: ${err}`;
      });
}

Any help/advice will be appreciated .Thanks

CKW
  • 51
  • 5
  • [`then`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) always returns a promise – pilchard Apr 25 '23 at 09:07
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – pilchard Apr 25 '23 at 09:08

1 Answers1

-1

you have to wait the for response.json().

export async function getMLRiskScore(params: any): Promise<any | null> {
    var mlScoringRequestPayload = { ... };
    
    const url = 'http://197.248.44.228:8600/openmrs/ws/rest/v1/keml/casefindingscore';
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
      },
      body: JSON.stringify(mlScoringRequestPayload),
   });


  const response = await response.json()
  
  // Your conditions and the appropriate return
  return 'my result'
}