大家好,我使用await关键字等待异步调用返回。我的网址是一个获取网址,所以如果我从浏览器中调用它,则会返回一个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()给我的回复
有人可以告诉我,我做错了什么。谢谢
答案 0 :(得分:1)
fetch(...)
返回一个承诺,你通过使用await解开这个承诺,所以这很好。但是response.json()
也会返回一个promise,所以你可能也希望对它使用await:
const response = await fetch(url)
const json = await response.json()
debugger
return json
注意:正如托马斯在评论中指出的那样 - 如果你只是在异步函数中返回response.json()
,你就不应该打开它 - 它无论如何都会被包含在另一个诺言中。这只是因为您进入调试器并尝试检查它需要从承诺中获取值。事实上,你的功能应该看起来更像这样:
getCustomerById: async (id) => {
const url = 'http://example.com/customer/' + id
return fetch(url).then((response) => response.json())
}
答案 1 :(得分:0)
你必须要理解的是,一旦你迈向未来(“我承诺这将最终返回一个值”),你永远不会回来进入同步逐步处理的枯燥安全的世界。
// 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) => { /* ... */ }
承诺是一个容器,您可以将所有容器传递给您。但要查看容器内部,您需要使用回调。
(或者使用async
/ await
,这只是.then
的语法糖。它会为你调用.then
,剩下的代码留在你的身上async
用作回调函数。)
因此,要获得结果,您需要等待承诺解决。这为您留下了两个选择:.then
或await
。
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
//
})()