【问题标题】:not getting correct data from promise没有从承诺中得到正确的数据
【发布时间】:2018-06-24 04:28:05
【问题描述】:

大家好,我正在使用 await 关键字来等待异步调用返回。我的 url 是一个获取 url,所以如果我从浏览器调用它,则会返回一个 json。问题是当我尝试从我的代码中获取数据时,它返回给我一个承诺,但我无法弄清楚如何从该承诺中获取数据响应

getCustomerById: async (id) => {

    try {
      const response = await fetch("http://www.ready.buzlin.com/buzlinApp/customer/getCustomerById.php?k=xxx&id=xxx");
      // console.log("Response Returned: "+ JSON.stringify(response));
      // resolve(response.json());
        debugger;
      return response.json();
    } catch (err) {
    }
  }

这就是 json.reponse() 返回给我的结果

谁能告诉我我做错了什么。谢谢

【问题讨论】:

  • 我认为这对您的问题没有帮助,但将响应声明为常量似乎很奇怪
  • 你能分享你想要获取数据的代码吗?
  • 这是我无法访问该代码的问题
  • “我无权访问该代码” 你能解释一下吗?您的方法getCustomerById 是如何调用/使用的?
  • 是的,当然getCustomerById 会返回一个承诺——这是一个async 函数!这有什么问题?

标签: javascript json async-await ecmascript-2017


【解决方案1】:

fetch(...) 返回一个promise,并且您正在使用await 解开该promise,这很好。但是response.json() 也返回了一个承诺,所以你可能还想在上面使用 await:

const response = await fetch(url)
const json = await response.json()
debugger
return json

注意:正如 Thomas 在评论中指出的那样——如果你只是在异步函数中返回 response.json(),你不应该打开它——无论如何它只会被另一个 Promise 包裹。只是因为您正在进入调试器并尝试检查它,您才需要从 Promise 中获取价值。事实上,你的函数应该看起来更像这样:

getCustomerById: async (id) => {
  const url = 'http://example.com/customer/' + id
  return fetch(url).then((response) => response.json())
}

【讨论】:

  • 没关系。异步函数中的return await somePromisereturn somePromise.then(value => value) 一样毫无意义。
【解决方案2】:

你必须明白的是,一旦你踏入未来(“我承诺这将最终返回一个值”),你将永远不会回来进入同步分步处理的无聊而安全的世界。

// It does not matter what you do inside this function or
// what you return. Because of the await keyword, this will
// **always** return a promise.
//
getCustomerById: async (id) => { /* ... */ }

promise 是一个容器,你可以随心所欲地传递这个容器。但是要查看容器内部,您需要使用回调。

(或者使用async/await,它只是.then的语法糖。在底层它为你调用.then,剩下的代码留在你的async函数中作为回调。 )

因此,要获得结果,您需要等待承诺解决。这让您有 2 个选择:.thenawait

const apiKey = 'some_crazy_long_string_you_got_from_somewhere_safe'
const baseUrl = 'http://www.ready.buzlin.com/buzlinApp/customer'

// Let's show the object this is attached to, so we can 
// actually make calls to the function.
//
const customerQueries = {
  getCustomerById: async (id) => {
    const url = `${baseUrl}/getCustomerById.php?k=${apiKey}&id=${id}`

    let response
    try {
      response = await fetch(url)
      return response.json()
    } catch (err) {
      // ... Properly handle error 
      // If you are not going to properly handle this error, then
      // don't catch it. Just let it bubble up.
    }
  }
}

// Or a cleaner looking alternative that is also more true to the
// underlying behavior by skipping all this `async/await` nonsense.
// 
const customerQueries2 = {
  getCustomerById: (id) => {
    const url = `${baseUrl}/getCustomerById.php?k=${apiKey}&id=${id}`

    return fetch(url)
      .then(response => response.json())
      .catch(err => {
        // ... Properly handle error
      })
}


// Now to get at the result
// 

// Using .then
customerQueries.getCustomerById(27)
  .then(customer => {
    //
    // ... Do something with customer
    // 
  })

// Or using async/await
(async () => {
  const customer = await customerQueries.getCustomerById(27)
  //
  // ... Do something with customer
  // 
})()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多