11.Generator应用

// 回调地狱
        $.ajax({
            url: 'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976',
            method: 'get',
            success(res) {
                console.log(res);

                // 继续发送请求
                $.ajax({
                    url: '',
                    method: 'get',
                    success(res1) {
                        // 发送ajax
                        $.ajax({
                            url: '',
                            method: 'get',
                            success(res2) {

                                // 发送ajax
                                $
                            }
                        })
                    }
                })
            }
        })

Generator 部署ajax操作,让异步代码同步化

function* main() {
            console.log('main');

            let res = yield request(
                'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976'
            )
            console.log(res);

            // 执行后面的操作
            console.log('数据请求完成,可以继续操作');

        }
        const ite = main();
        ite.next();

        function request(url) {
            $.ajax({
                url,
                method: 'get',
                success(res) {
                    console.log(ite.next(res));
                }
            })
        }

 

原文地址:https://www.cnblogs.com/sunny666/p/12986590.html