fetch与Promise实战应用

fetch基于Promise进行设计的,用于同Ajax发起获取资源的请求,返回一个promise。

example: 模拟登录post请求
react-native绑定点击登陆事件
 
方法1 es6箭头函数实现
 LogIn() {
        let params = {
          username: 'charles1',
          password: '123456'
        }
        fetch('http://192.168.3.103:9999/api/users/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(params)
        })
        .then((res) => {
          return res.json();
        })
        .then((json) => {
          console.log(json)
        })
        .catch(function(e) {
          console.log("Oops, error");
        })
    }
方法2 async,await使用
    async LogIn() {
        let params = {
          username: 'charles1',
          password: '123456'
        }
        try {
            let response = await fetch('http://192.168.3.103:9999/api/users/login', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(params)
            })
           let dataPromise = await response.json();
           console.log(dataPromise)
        } catch(err) {
            console.log(err)
        }
    }

你可能感兴趣的:(react-native开发)