-2

I just recently asked this question below, I was referred to this question, and my question was closed. Fair enough. I read through that question prior though and after and still don't understand where I am too create a promise and resolve it. See I need to return a status and a message in this async function that wraps my code, and I can't return it inside the .then(data=>{console.log(data.success)}

Do I create a promise inside the .then, what I am trying to do is get the data.success into the res variable properly, instead of the way I am doing it which is creating an empty variable and assigning it in the .then. I know this is incorrect.

If someone could just point me in the right direction with some comment or something that would help. I have read the referred question, and see how it applies but don't know how to implement it in my context.

Initial Question snippet Below

I'm wondering if there is a better way than creating a let variable outside this fetch request, assigning it inside, and then using it later on. Here is my code so far. Is there a way to have the res variable return the value in the data.success inside the .then

let isItTrue

const res = await fetch(fetchUrl, {
    method: "POST",
    body: JSON.stringify({ message: "hello world" }),
    headers: { "Content-Type": "application/json" },
  })
    .then(response => response.json())
    .then(data => {
      isItTrue = data.success
      console.log(data)
      console.log(data.success)
    })
    .catch(error => {
      console.error("Error:", error)
    })

if(isItTrue){
  //DO SOMETHING
const isItTrueSomething = "success"
}

I am eventually returning something in the same scope as the if statement, this is all inside a async serverless function.


  return {
    statusCode: 200,
    body: JSON.stringify({ message: isItTrueSomething }),
  }

I want to return the status from fetch inside the return of this serverless function

require("dotenv").config()
const sgMail = require("@sendgrid/mail")
const {
  SENDGRID_API_KEY,
  SENDGRID_TO_EMAIL,
  SENDGRID_TO_EMAIL_TEST,
} = process.env
const URL = require("url")
const https = require("https")
const fetch = require("node-fetch")

// Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method
const handler = async event => {
  //  try {
  const body = JSON.parse(event.body)

  let secret = process.env.GOOGLE_CAPTCHA_SECRET
  const fetchUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${body.dataMassage.captcha}&remoteip=${event.headers["client-ip"]}`

  console.log(fetchUrl)

  const res = await fetch(fetchUrl, {
    method: "POST",
    body: JSON.stringify({ message: "hello world" }),
    headers: { "Content-Type": "application/json" },
  })
    .then(response => response.json())
    .then(data => {
      // isItTrue = data.success
      console.log(data)
      console.log(data.success)
    })
    .catch(error => {
      console.error("Error:", error)
    })


  // console.log(body)
  const subject = event.queryStringParameters.name || "World"
  return {
    statusCode: 200,
    body: JSON.stringify({ message: `FETCH_STATUS` }),
  }
  // } catch (error) {
  // return { statusCode: 500, body: error.toString() }
  // }
}

module.exports = { handler }
Anders Kitson
  • 1,413
  • 6
  • 38
  • 98
  • 1
    Given that you're awaiting, why don't you just return data.success from the second then callback? res is going to be undefined otherwise, since you don't currently return anything. Or if you want the response object *and* the payload somewhere, maybe look at https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain. But right now it's unclear what output you're looking for. – jonrsharpe Mar 24 '21 at 20:05
  • I will try that, I tried before but If I remember correctly, the call I made to the serverless function never returne the status code and body so it errored at on the client requesting to the serverless function. Let me try though – Anders Kitson Mar 24 '21 at 20:07
  • What serverless function? What *error*? – jonrsharpe Mar 24 '21 at 20:09
  • 1
    If you look at the initial question https://stackoverflow.com/questions/66786474/how-would-i-get-a-variable-outside-of-a-fetch-then-response-json-then-so-that/66786558#66786558 and I move the return statement inside the final .then, I get a 500 response. I am using Gatsby JS to run a fetch request to this serverless function. In the initial question the entire function is in the bottom. Where I am returning the status code I want to return the value from fetch – Anders Kitson Mar 24 '21 at 20:12
  • Please put a [mre] *in this question*, it should stand alone. But again, why don't you just return the value you want from the then callback, so res gets that value? What you're showing is something that doesn't *try* to get or use that value, so it's no surprise it doesn't work. – jonrsharpe Mar 24 '21 at 20:18
  • ok will try to do so – Anders Kitson Mar 24 '21 at 20:21
  • Oh I am so dumb, I now know what you meant by returning inside the .then. It is working now. Geez, I feel stupid – Anders Kitson Mar 24 '21 at 20:25

1 Answers1

0

It shouldn't be any more complicated than this:

async function checkIsItTrue() {

  // await waits until the promise chain settles and hands back
  // the resolved value of the promise (or throws if the promise is rejected)
  const isItTrue = await fetch(fetchUrl, {
    method: "POST",
    body: JSON.stringify({ message: "hello world" }),
    headers: { "Content-Type": "application/json" },
  })
  .then( response => response.json())
  .then( data => data.success );

  // And an async function returns a promise.
  // And. . . since 'isItTrue' is a boolean value, we know that it will be a resolved promise
  return isItTrue;
}

All you have to do then is to say:

const isItTrue = await checkIsItTrue();
if (isItTrue) {
  doSomethingIfTrue();
} else {
  doSomethingElseIfNotTrue();
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135