美文网首页
12、【ES6】Promise

12、【ES6】Promise

作者: yscyber | 来源:发表于2021-09-28 21:15 被阅读0次
  • Promise 是 ES6 引入的异步编程的新解决方案。语法上 Promise 是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果。
    let p = new Promise(function(resolve, reject) {
        // 模拟一个异步操作,比如网络请求
        setTimeout(function() {
            let resp = 'data';
            // 异步操作成功的话,调用 resolve 反之调用 reject,传入异步操作获取的数据
            // 即成功或失败后续的具体逻辑不再此处编写
            resolve(resp);
        }, 1000);
    });

    // 使用 then 方法来编写后续的逻辑
    p.then(function(value) {
        // 成功的具体的逻辑
        console.log(value); // 因为上面的是 resolve,所以这里执行
    }, function(reason) {
        // 失败的具体逻辑
        console.log(reason);
    });
    // Promise 原生 Ajax

    const url = 'http://poetry.apiopen.top/sentences';

    const requestPromise = new Promise(((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.send();

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status <= 299) {
                    resolve(xhr.response);
                } else {
                    reject(xhr.status);
                }
            }
        };
    }));

    requestPromise.then(value => {
        console.log(value);
    }, reason => {
        console.log(reason);
    });
    const correctUrl = 'http://poetry.apiopen.top/sentences';
    const errorUrl = 'http://poetry.apiopen.top/sentenc';

    const requestPromise = new Promise(((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', errorUrl);
        xhr.send();

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status <= 299) {
                    resolve(xhr.response);
                } else {
                    reject(xhr.status);
                }
            }
        };
    }));

    requestPromise.then(value => {
        console.log(value);
    });

    // 当 then 方法中没有提供 reject 对应的回调时,可以使用 catch
    requestPromise.catch(reason => {
        console.warn(reason);
    });
  • then方法的返回值仍是一个 Promise。

相关文章

网友评论

      本文标题:12、【ES6】Promise

      本文链接:https://www.haomeiwen.com/subject/ccszgltx.html