我一生都在努力理解 fetch()/async/await。我希望能够执行我的异步函数、检索响应并传递响应。然而,我的键盘的按键都因为我的头撞坏了。预先感谢您。
async function makeCall() {
var restHostConfig = await fetch("https://httpbin.org/ip")
var body = await restHostConfig.json();
console.log("First this: " + JSON.stringify(body)); // Prints {"origin":"IP address"} Nice!
return body;
}
const callComplete = makeCall().then((response) => {
console.log("Now this: " + JSON.stringify(response)); // Prints {{"origin":"IP address"} Okay!
var resolve = JSON.stringify(response);
return resolve;
})
// At this point, below should print {{"origin":"IP address"} right? Wrong. It is a Promise object in which I have no idea at this point how to resolve into the response body.
console.log("Finally this log: " + retrieveResponse); // I get it if this is pleb status.```
只需调用 makeCall() 就应该给出结果,为什么要通过另一个函数传递它。
async function makeCall() {
var restHostConfig = await fetch("https://httpbin.org/ip")
var body = await restHostConfig.json();
console.log("First this: " + JSON.stringify(body)); // Prints {"origin":"IP address"} Nice!
return body;
}
makeCall();
如果这不是您想要的结果,您能简单描述一下您想要的值是什么样子吗?