Search code examples
javascriptes6-promiseundefined-function

promise executing function returning undefined


I am trying to return a value inside of a promise when the promise resolves, then pass the returned value to my state. However, the return value of my function no matter what I try... is undefined.

My function is imported from an npm package which has its documentation here: https://www.npmjs.com/package/synonyms

it is meant to return a synonym of a given word.

Maybe there is some really obvious issue with the way I structured the promise itself that is causing some bad async timing?

I have tried returning only the function without passing it to resolve but this throws an error

searchForSynonymsAndDef = (param) =>{
if(this.state.scholarMode==true){
console.log("INSIDE SYNONYMS")

var synonyms = require("synonyms");

  let p = new Promise((resolve,reject,param)=>{
    var result=resolve(synonyms(param,"n"))

  }).then((result)=>{
    console.log("result is:",result)
  })
  .then((result)=>{
    this.setState({textToReadAloud: "here are some synonyms for "
    +param +"...firstly.....nouns...."+result})
    console.log("here are some synonyms for "+param +"...firstly.....nouns...."+result)
    })
  }else{
    console.log("sorry scholar mode is off")
  }
}

I expect 'result' to be a synonym based on the passed in param but unfortunately result is always = undefined :(


Solution

  • You don't need to pass param to promise. Just remove param from Promise and it should work.

    searchForSynonymsAndDef = (param) =>{
    if(this.state.scholarMode==true){
    console.log("INSIDE SYNONYMS")
    
    var synonyms = require("synonyms");
    
      let p = new Promise((resolve,reject)=>{
        var result=resolve(synonyms(param,"n"))
    
      }).then((result)=>{
        console.log("result is:",result)
      })
      .then((result)=>{
        this.setState({textToReadAloud: "here are some synonyms for "
        +param +"...firstly.....nouns...."+result})
        console.log("here are some synonyms for "+param +"...firstly.....nouns...."+result)
        })
      }else{
        console.log("sorry scholar mode is off")
      }
    }