【问题标题】:returning a resolved a Promise of a fetch request [duplicate]返回已解决的获取请求的承诺 [重复]
【发布时间】:2021-06-21 14:24:17
【问题描述】:

我最近刚刚在下面问了这个问题,我被提到了this 问题,我的问题被关闭了。很公平。我之前和之后都通读了这个问题,但仍然不明白我在哪里创建一个承诺并解决它。请参阅我需要在包装我的代码的这个异步函数中返回一个状态和一条消息,而我无法在 .then(data=>{console.log(data.success)} 中返回它

我是否在 .then 中创建了一个承诺,我想要做的是将 data.success 正确地放入 res 变量中,而不是我这样做的方式是创建一个空变量并将其分配到。然后。我知道这是不正确的。

如果有人能用一些评论或一些有帮助的东西为我指明正确的方向。我已经阅读了提到的问题,并了解它是如何应用的,但不知道如何在我的上下文中实现它。

Initial Questionsn-p 下面

我想知道是否有比在这个 fetch 请求之外创建一个 let 变量、在内部分配它然后稍后使用它更好的方法。到目前为止,这是我的代码。有没有办法让 res 变量返回 .then 内的 data.success 中的值

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

我想在这个无服务器函数的返回中返回 fetch 的状态

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 }

【问题讨论】:

  • 鉴于您正在等待,为什么不直接从第二个 then 回调中返回 data.success 呢? res 否则将是未定义的,因为您当前不返回任何内容。或者,如果您希望在某处获得响应对象和有效负载,请查看stackoverflow.com/questions/28250680/…。但现在还不清楚您要寻找什么输出。
  • 我会尝试,我之前尝试过,但如果我没记错的话,我对无服务器函数的调用永远不会返回状态代码和正文,因此它在客户端请求无服务器函数时出错。让我试试吧
  • 什么无服务器功能?什么错误?
  • 如果您查看最初的问题 stackoverflow.com/questions/66786474/… 并将 return 语句移到最后的 .then 中,我会得到 500 响应。我正在使用 Gatsby JS 运行对这个无服务器函数的获取请求。在最初的问题中,整个功能都在底部。在我返回状态码的地方,我想从 fetch 中返回值
  • 请把minimal reproducible examplein this question,它应该是独立的。但是,为什么不直接从 then 回调中返回你想要的值,让 res 得到那个值呢?您所展示的是不会尝试获取或使用该值的东西,因此它不起作用也就不足为奇了。

标签: javascript node.js async-await promise


【解决方案1】:

应该不会比这更复杂:

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

你所要做的就是说:

const isItTrue = await checkIsItTrue();
if (isItTrue) {
  doSomethingIfTrue();
} else {
  doSomethingElseIfNotTrue();
}

【讨论】:

  • 如果你在那里等待的只是返回值,为什么要让它成为一个异步函数?
  • 因为你只能在异步函数中await。
  • 还有……等待它有什么意义?你的函数可能只是return fetch(fetchUrl, {... 不需要等待任何东西。
  • 那么你没有得到 promise 的解析值。你必须在then() 链中做所有事情。
  • 你在说什么?如果您返回链,您将收到该链的返回值。
猜你喜欢
  • 1970-01-01
  • 2021-05-25
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 2018-11-09
相关资源
最近更新 更多