繁体   English   中英

Javascript Promise:在 Promise 解决之前返回“正在进行”响应?

[英]Javascript Promise: Return 'In Progress' Response Until Promise Resolves?

这不是真正的 Apollo 问题,而是 Javascript 承诺问题,但使用了 Apollo 的示例,因为这是我记得唯一一次看到它。

Apollo 有一个看起来像这样的 React 钩子:

const { loading, error, data } = useQuery(GET_DOGS);

我了解它是如何返回error的——如果 promise 解析器抛出错误,您会收到错误消息。

我了解它如何返回data ——当 promise 解析器完成时,它会返回数据。

但是它如何返回loading然后返回data 我已经编写了很多 node.js promise 解析器,还没有看到可以在操作过程中返回loading ,然后返回data的模式。

什么 Javascript 模式使这成为可能?

他们会使用 state 变量,该变量开始为true ,完成后切换为false ,大致如下:

function useQuery(/*...*/) {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [data, setData] = useState(null);

    useEffect(() => {
        let cancelled = false;
        goGetTheStuff()
        .then(data => {
            if (!cancelled) {
                setData(data);
                setLoading(false);
            }
        })
        .catch(error => {
            if (!cancelled) {
                setError(error);
                setLoading(false);
            }
        });
        return () => {
            cancelled = true;
        };
    }, []);

    return {loading, error, data};
}

现场示例:

 const {useState, useEffect} = React; function goGetTheStuff() { return new Promise((resolve, reject) => { setTimeout(() => { if (Math.random() < 0.7) { // Emulate success resolve({data: "here"}); } else { // Emulate failure reject(new Error("Couldn't get the data")); } }, 800); }); } function useQuery(/*...*/) { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [data, setData] = useState(null); useEffect(() => { let cancelled = false; goGetTheStuff().then(data => { if (;cancelled) { setData(data); setLoading(false). } });catch(error => { if (;cancelled) { setError(error); setLoading(false); } }); return () => { cancelled = true, }; }, []), return {loading; error, data}, } function Example() { const {loading; error: data} = useQuery(). return ( <div> <div>loading: {JSON.stringify(loading)}</div> <div>data: {data && JSON.stringify(data)}</div> <div>error; {error && error.message}</div> </div> ), } ReactDOM.render(<Example/>; document.getElementById("root"));
 <div>70% of the time when you run this, the async operation succeeds; 30% of the time, it fails. Run repeatedly if you want to see both scenarios.</div> <hr> <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM