0

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 :(

1
  • Get rid of the first then(). You don't return anything to it so the next then() is seeing undefined Commented Oct 2, 2019 at 2:47

2 Answers 2

0

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")
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help now the code runs but my result is simply 'undefined'
could this perhaps be an issue with the way I am including my 'synonyms'
0
searchForSynonymsAndDef = (param) =>{
    if(this.state.scholarMode==true){
    console.log("INSIDE SYNONYMS")

    var synonyms = require("synonyms");
    let p = new Promise((resolve,reject,param)=>{
        resolve(synonyms(param,"n"));
    });
    return p;
}else{
    console.log("sorry scholar mode is off")
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.