0
点赞
收藏
分享

微信扫一扫

Promise异步编程

小磊z 2022-03-11 阅读 81
javascript

promise是ES6引入的异步编程的解决方案,是一个构造函数,用来封装异步操作并可以获取其成功和失败的结果。

// promise异步编程
    const p = new Promise(function(resolve, reject) {
      setTimeout(function() {
        let data = '成功的数据';
        resolve(data);
        let err = '错误的数据';
        reject(err);
      }, 2000)
    })
    p.then(function(value) {
      console.log(value)
    }, function(error) {
      console.log(error)
    })

const readPro = new Promise(function(resolve, reject) {
    fs.readFile('./utils.js', (err, data) => {
        if(err) reject(err);
        resolve(data);
    })
  })
  readPro.then(function(value) {
    console.log(value)
  }, function(error) {
    console.log(error)
  });
// promise 网络请求
const apiPro = new Promise(function(resolve, reject) {
    const xml = new XMLHttpRequest();
    xml.open('GET', 'https://api.open/get');
    xml.send();
    xml.onreadystatechange = function() {
        if(xml.readyState === 4) {
            if(xml.status >= 200 && xml.status < 300) {
                resolve(xml.response)
            } else {
                reject(xml.status)
            }
        }
    }
  })
  apiPro.then(function(value) {
    console.log(value)
  }, function(error) {
    console.log(error)
  });
举报

相关推荐

0 条评论