我有以下useEffect回调函数:-
import { initDB, useIndexedDB } from "react-indexed-db";
initDB(DBConfig);
const db = useIndexedDB("reads");
useEffect(() => {
db.getByIndex("hash", props.match.params.id).then((data) => {
setToken(data.token);
});
handleTextColorSelection(backgroundColor);
axios
.post(`${process.env.REACT_APP_API_URL}khatma/read`, {
khatma: props.match.params.id,
part: props.match.params.part,
section: props.match.params.section,
token: token,
})
.then((res) => {
if (res.data.token) {
db.add({
hash: props.match.params.id,
token: res.data.token,
}).then(
(event) => {},
(error) => {
console.log(error);
}
);
}
})
在axios发布主体中,我正在发送令牌,如果“令牌”状态接收到以前存储在浏览器索引db中的值,如果没有找到对象存储数据,则发布令牌将作为null发送。
这里的问题是,我注意到,在db.getByIndex(“ hash”,...命令获得结果之前,将运行axios请求,并将令牌发送为null,尽管稍后在令牌状态下将获得一个值。
如何运行db.getByIndex(“ hash”,如果完成,请运行axios发布请求?
答案 0 :(得分:0)
您可以使用.then
const axiosRequest = () => { /* your axios logic */ };
db.getByIndex(...).then(axiosRequest).catch(axiosRequest)
在then
调用之后,将在catch
和getByIndex
回调中执行所有操作