Hướng dẫn is fetch blocking javascript? - tìm nạp có chặn javascript không?

Nếu bạn đã sử dụng JavaScript được một thời gian, có lẽ bạn đã sử dụng Fetch API ES6. Nó thực sự thú vị , đặc biệt là vì nó liên quan đến các phương thức JavaScript không đồng bộ. Hãy cùng tìm hiểu cách sử dụng async await vs fetch nhé.

Một chút về Fetch

Sử dụng

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
3 có thể được coi là sử dụng API cấp thấp hơn để thực hiện các nhu cầu của bạn để trả về phản hồi từ URI, nói cách khác là không dùng framework hoặc thư viện.

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
4 đã được giới thiệu để các nhà phát triển có thể dễ dàng thực hiện các yêu cầu tới các điểm cuối của URI hoặc phần còn lại cho các ứng dụng.

Trước đó, tiêu chuẩn là sử dụng các yêu cầu ajax chúng ta thường dùng

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
5, ex:
async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
6 . Nó không tệ và vẫn tồn tại rất nhiều code kế thừa ngoài kia, vì vậy bạn cũng nên hiểu về cách thức hoạt động của nó và nguồn gốc của
async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
7, vì đây là tiêu chuẩn trước khi
async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
8 xuất hiện.

Promise Code

Đoạn mã dưới đây không tệ, và nó hoạt động chính xác, tuy nhiên, có một vài điều về nó làm cho nó rối rắm ở đây. Lưu ý

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
9 function, nó hỗ trợ callback function để giải quyết, xử lý kết quả cho
async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
3 function.

Nó trông khá là dễ đọc đối với đoạn code ngắn. Tuy nhiên, có sự xâu chuỗi của

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
9 và điều này có thể dẫn đến cái thường được gọi là callback hell, hoặc nhiều callback lồng nhau. Điều đó làm giảm khả năng đọc hiểu code và có thể dễ dàng ảnh hưởng đến hiệu suất hoặc xuất hiện một vài con bugs.

function getUser(name){
 fetch(`https://api.github.com/users/${name}`)
  .then(function(response) {
    return response.json();
  })
  .then(function(json) {
    console.log(json);
  });
};

//get user data
getUser('yourUsernameHere');

Sử dụng Async/Await với Fetch API

Sử dụng Async/Await không được hỗ trợ đầy đủ trên tất cả các trình duyệt. Vì vậy, bạn nên biết điều này, và kiểm tra nhu cầu của bạn khi phát triển.

Bạn có thể kiểm tra trình duyệt hỗ trợ Async/Await tại đây, và trình duyệt hỗ trợ fetch function tại đây. Hãy nhớ rằng để gọi một hàm bằng từ khóa

async function doSomethingAsync() {
    try {
        // This async call may fail.
        let result = await getUserAsync('yourUsernameHere') ;
    } catch (error) {
        // If it does we will catch the error here.
    }
}
Or
getUserAsync('yourUsernameHere')
    .then(data => {
        console.log(data)
    }).catch(error => {
            console.log('request failed', error)
        }
    );
2, nó phải nằm trong hàm
async function doSomethingAsync() {
    try {
        // This async call may fail.
        let result = await getUserAsync('yourUsernameHere') ;
    } catch (error) {
        // If it does we will catch the error here.
    }
}
Or
getUserAsync('yourUsernameHere')
    .then(data => {
        console.log(data)
    }).catch(error => {
            console.log('request failed', error)
        }
    );
3 như trong ví dụ dưới đây.

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  

Xử lý lỗi

async function doSomethingAsync() {
    try {
        // This async call may fail.
        let result = await getUserAsync('yourUsernameHere') ;
    } catch (error) {
        // If it does we will catch the error here.
    }
}
Or
getUserAsync('yourUsernameHere')
    .then(data => {
        console.log(data)
    }).catch(error => {
            console.log('request failed', error)
        }
    );

Xem thêm :

  • 50+ thuộc tính thú vị trong CSS
  • Cài đặt WordPress với Caddy web server trên Ubuntu 18.04
  • Hướng Dẫn Tạo VPS Azure Cấu Hình Cao 4h Băng Thông Khủng Miễn Phí Từ Microsoft

Nội dung bài viết

Video học lập trình mỗi ngày

Fetch api là gì? Trước đây nếu bạn nào đã từng sử dụng XMLHttpRequest để giao tiếp lấy dữ liệu từ server đến client hay ngược lại thì cũng sẽ hiểu nôm na Fetch api javascript cũng vậy. Fetch api cho phép những nhà phát triển lấy resource và thực hiện những yêu cầu thông qua http.

Trước đây chúng tôi có đề cập đến bài viết request api trong Nodejs "3 cách để thực hiện các yêu cầu HTTP (Http request) trong Node.js" nhưng không đề cập đến thằng này (Fetch) vì sao??? Đoán thử xem nào?"3 cách để thực hiện các yêu cầu HTTP (Http request) trong Node.js" nhưng không đề cập đến thằng này (Fetch) vì sao??? Đoán thử xem nào?

Fetch api là gì?

Nói cho sang vậy thôi chứ bất cứ thằng lập trình nào mà chẳng biết đến nó (XMLHttpRequest) và sau này sử dụng jquery với ajax để sử dụng post, get... Hồi ajax mới ra, ai mà sử dụng được dụng jquery.ajax cũng là pro lắm rồi. Làm bao nhiêu việc như add html, change value mà không reload lại page, tổ chức các kiểu này nọ. Khiếp lắm, giờ đỡ rồi :D. Sau một thởi gian thì, developers cũng thấy những bất cập khi sử dụng ajax, hay XMLHttpRequest và quay sang ủng hộ native APIs. Và hôm nay, chúng ta cùng đàm đạo về một api đó là fetch. Nhưng khi nói về fetch thì chúng ta cũng nên quên rằng có một api cũng rất mạnh và cũng đang được những lập trình viên sử dụng rộng rãi đó là axios. Nhưng để chỉ ra những điểm khác nhau giữa fetch và aixos thì các bạn nên tìm hiểu kỹ, vì mỗi cái áp dụng khác nhau.

Hướng dẫn is fetch blocking javascript? - tìm nạp có chặn javascript không?

Phương thức fetch () nhìn chung rất hiện đại và linh hoạt, chính vì vậy chúng ta sẽ xem qua một số chức năng mà fecth có thể xử lý được. Nhưng lưu ý, fetch() có thể sẽ không được hỗ trợ với các browser cũ, nhưng nhìn chung thì điều đó không đáng bận tâm, vì hầu hết chúng ta đều sử dụng những browser hiện đại hơn. 

Xem fetch() support browser

Cú pháp cơ bản Fetch api

let promise = fetch(url, [options])

* url – the URL to access. * options – optional parameters: method, headers etc.

GET Requests with Fetch API

Ở trường hợp nào đó đó chúng ta muốn nhận một json tử một API nào đó, trường hợp này thì gặp nhiều đa số là mấy thằng làm với REST API

fetch('https://api.github.com/orgs/nodejs')
.then(response => response.json())
.then(data => {
  console.log(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))

Custom headers

Có thể add headers nếu muốn

ví dụ :

fetch('https://api.github.com/orgs/nodejs', {
  headers: new Headers({
    'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
})
.then(response => response.json())
.then(data => {
  console.log(data)
})
.catch(error => console.error(error))

Gửi thông tin xác thực với Fetch

Để gửi kèm thông tin xác thực cookie (user là ai), chúng ta truyền tham số credentials: include

fetch('https://api.github.com/orgs/nodejs', {
  credentials: 'include', // Useful for including session ID (and, IIRC, authorization headers)
})
.then(response => response.json())
.then(data => {
  console.log(data) // Prints result from `response.json()`
})
.catch(error => console.error(error))

Notes: Ở đây ông lập trình nào khi sử dụng credentials: 'include' bị lỗi này "blocked by CORS" thì sử dụng credentials: "same-origin"

POST/PUT Requests

postRequest('http://example.com/api/v1/users', {user: 'Dan'})
  .then(data => console.log(data)) // Result from the `response.json()` call
  .catch(error => console.error(error))

function postRequest(url, data) {
  return fetch(url, {
    credentials: 'same-origin', // 'include', default: 'omit'
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json'
    }),
  })
  .then(response => response.json())
}

Posting an HTML 

postForm('http://example.com/api/v1/users')
  .then(data => console.log(data))
  .catch(error => console.error(error))

function postForm(url) {
  const formData = new FormData(document.querySelector('form.edit-user'))

  return fetch(url, {
    method: 'POST', // or 'PUT'
    body: formData  // a FormData will automatically set the 'Content-Type'
  })
  .then(response => response.json())
}

Form encoded data

postFormData('http://example.com/api/v1/users', {user: 'Mary'})
  .then(data => console.log(data))
  .catch(error => console.error(error))

function postFormData(url, data) {
  return fetch(url, {
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: new URLSearchParams(data),
    headers: new Headers({
      'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    })
  })
  .then(response => response.json())
}

Uploading files

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
0

Uploading multiple files

Trên client là như thế này.

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
1

Cách sử dụng.

async function getUserAsync(name) {
    let response = await fetch(`https://api.github.com/users/${name}`);
    let data = await response.json()
    return data;
}

getUserAsync('yourUsernameHere').then(data => console.log(data));  
2

Thật ra nói cho hay vậy chứ thấy axios ngon hơn nhiều há há, Để lần sau post về axios rồi so sánh cho anh em một phát. Giờ thì test thử xem nó hay ho thế nào.

Anh em nào muốn đọc kỹ hơn thì link đây: https://gist.github.com/justsml/529d0b1ddc5249095ff4b890aad5e801