axios 库创建一个 Promise() 对象。 Promise 是 JavaScript ES6 中的内置对象。当使用 new 关键字实例化此对象时,它需要一个函数作为参数。这个单一的函数又接受两个参数,每个参数也是函数——resolve和reject。
Promises 执行客户端代码,并且由于 cool Javascript 异步流程,最终可以解决一两件事,即解决方案(通常认为在语义上等同于 Promise 的成功),或者该拒绝(被广泛认为是错误的解决方案)。例如,我们可以持有对某个 Promise 对象的引用,该对象包含一个最终返回响应对象(将包含在 Promise 对象中)的函数。因此,我们可以使用这样的 Promise 的一种方法是等待 Promise 解析为某种响应。
您可能会提出我们不想等待几秒钟左右让我们的 API 返回调用!我们希望我们的 UI 能够在等待 API 响应时做一些事情。否则,我们将拥有一个非常缓慢的用户界面。那么我们如何处理这个问题呢?
Promise 是异步的。在负责执行 Javascript 代码的引擎(例如 Node 或普通浏览器)的标准实现中,它将在另一个进程中解析,而我们事先不知道 promise 的结果是什么。通常的策略是然后发送我们的函数(即一个类的 React setState 函数)到 Promise,根据某种条件(取决于我们选择的库)来解决。这将导致我们的本地 Javascript 对象根据 Promise 解析进行更新。因此,您可以考虑可能发送到异步方法的函数,而不是 getter 和 setter(在传统 OOP 中)。
我将在此示例中使用 Fetch,以便您可以尝试了解 Promise 中发生了什么,看看您是否可以在您的 axios 代码中复制我的想法。 Fetch 与 axios 基本相似,没有先天的 JSON 转换,并且具有不同的 promise 解析流程(您应该参考 axios 文档来学习)。
GetCache.js
const base_endpoint = BaseEndpoint + "cache/";
// Default function is going to take a selection, date, and a callback to execute.
// We're going to call the base endpoint and selection string passed to the original function.
// This will make our endpoint.
export default (selection, date, callback) => {
fetch(base_endpoint + selection + "/" + date)
// If the response is not within a 500 (according to Fetch docs) our promise object
// will _eventually_ resolve to a response.
.then(res => {
// Lets check the status of the response to make sure it's good.
if (res.status >= 400 && res.status < 600) {
throw new Error("Bad response");
}
// Let's also check the headers to make sure that the server "reckons" its serving
//up json
if (!res.headers.get("content-type").includes("application/json")) {
throw new TypeError("Response not JSON");
}
return res.json();
})
// Fulfilling these conditions lets return the data. But how do we get it out of the promise?
.then(data => {
// Using the function we passed to our original function silly! Since we've error
// handled above, we're ready to pass the response data as a callback.
callback(data);
})
// Fetch's promise will throw an error by default if the webserver returns a 500
// response (as notified by the response code in the HTTP header).
.catch(err => console.error(err));
};
现在我们已经编写了 GetCache 方法,让我们看看更新 React 组件状态的例子......
一些 React Component.jsx
// Make sure you import GetCache from GetCache.js!
resolveData() {
const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.
const setData = data => {
this.setState({
data: data,
loading: false
// We could set loading to true and display a wee spinner
// while waiting for our response data,
// or rely on the local state of data being null.
});
};
GetCache("mySelelection", date, setData);
}
最终,您不会像这样“返回”数据,我的意思是您可以,但改变您的思维方式更为惯用......现在我们正在发送数据到异步方法。
编码愉快!