Trang chủ » Blog » [Thực hành] Kiến thức về Promise- Codegym.vn

[Thực hành] Kiến thức về Promise- Codegym.vn

bởi CodeGym | 26/12/2023 17:16 | Bài thực hành | Blog

Mục tiêu

Thực hành kiến thức về Promise.

Mô tả- promise

  • Clone project rỗng để bắt đầu code.
  • Cài đặt các package cần thiết.
  • Code các phần code mẫu.
  • Chạy để kiểm tra kết quả đạt được.

Hướng dẫn

Bước 1:  Truy cập vào https://github.com/codegym-vn/typescript-demo , đọc README, clone dự án.

Bước 2: Thực thi lệnh npm i tại thư mục dự án vừa clone về, để cài đặt các packages cần thiết.

Bước 3: Mở dự án mẫu với editor mà các bạn quen thuộc

promise

Bước 4: Chạy lệnh npm start, sau đó trình duyệt sẽ tự động mở trang web localhost:3000, các bạn có thể nhìn thấy danh mục bài học như sau:

Bước 5: Di chuyển vào link của bài học 6.

Bước 6: Mở file src/promise.ts trong project vừa tạo, sau đó code lần lượt các đoạn code sau:

============================================
const wait5Secs = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(5);
    }, 5000);
});

wait5Secs.then(data => console.log(data)).catch(err => console.error(err));

Expected:
    Sau 5 giây sẽ in ra “5”.

============================================
// promise chỉ resolve hoặc reject duy nhất 1 lần
const promise = new Promise((resolve, reject) => {
    resolve('done');
    reject(new Error('…')); // ignored
    setTimeout(() => resolve('…')); // ignored
});

promise.then(data => console.log(data));
Expected:
    In ra “done”
============================================
function httpGet(url: string): Promise<any> {
    return new Promise(function(resolve, reject) {
        const request = new XMLHttpRequest();
        request.onload = function() {
            if (this.status === 200) {
                // Success
                resolve(this.response);
            } else {
                // Something went wrong (404 etc.)
                reject(new Error(this.statusText));
            }
        };
        request.onerror = function() {
            reject(new Error('XMLHttpRequest Error: ' + this.statusText));
        };
        request.open('GET', url);
        request.send();
    });
}
httpGet('https://api.github.com/search/repositories?q=angular').then(
    function(value) {
        console.log('Contents: ' + value);
    },
    function(reason) {
        console.error('Something went wrong', reason);
    }
);
// parseJSON
function parseResponse(value: string) {
    try {
        return JSON.parse(value);
    } catch (_) {
        return value;
    }
}
httpGet('https://api.github.com/search/repositories?q=angular')
    .then(parseResponse)
    .then(data => console.log(data))
    .catch(function(reason) {
        console.error('Something went wrong', reason);
    });



Expected:
    Nếu request thành công sẽ in ra dữ liệu seach.
============================================
/**
 * Async/Await
 */
async function f() {
    return 1;
}

function fp() {
    return Promise.resolve(1);
}

f().then(data => console.log('async fn', data));

(async() => {
    const data = await fp();
    console.log('async/await', data);
})();

Expected:
    async fn 1
async/await 1
============================================
async function fns() {
    const promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("done!"), 1000)
    });
    // wait till the promise resolves (*)
    const result = await promise;
    console.log(result); // "done!"
}

fns();

Expected:
    Sau 1 giây sẽ in ra “done!”
============================================
// handle error
async function getUser(username: string) {
    try {
        const response = await fetch(
            `https://api.github.com/search/users?q=${username}`
        );
        return await response.json();
    } catch (e) {
        throw e;
    }
}
getUser('bob')
    .then(res => console.log(res))
    .catch(err => console.warn(err));

Expected:
    Nếu request thành công sẽ in ra dữ liệu seach.
============================================
// do not combine sync operations with async/await
(() => {
    let x = 0;
    async function r5() {
        x += 1;
        console.log(x);
        return 5;
    }

    (async () => {
        x += await r5();
        console.log(x);
    })();
})();

// fixed version
(() => {
    let x = 0;
    async function r5() {
        x += 1;
        console.log(x);
        return 5;
    }

    (async () => {
        const y = await r5();
        x += y;
        console.log(x);
    })();
})();

Expected:
    1
1
5
6
============================================
// Too Sequential
async function fetchAllBook() {
    await new Promise(resolve => {
        console.log('Waiting 2s...');
        setTimeout(() => resolve(), 2000);
    });
    console.log('fetchAllBook');
    return [
        {
            id: 'book-id-1',
            authorId: 'author-id-1'
        }, {
            id: 'book-id-2',
            authorId: 'author-id-2'
        }, {
            id: 'book-id-3',
            authorId: 'author-id-3'
        }
    ];
}

async function fetchAuthorById(authorId: string) {
    console.log('fetchAuthorById');
    return {
        authorId,
    };
}
async function getBooksAndAuthor(authorId: string) {
    const books = await fetchAllBook();
    const author = await fetchAuthorById(authorId);
    return {
        author,
        books: books.filter(book => book.authorId === authorId),
    };
}

getBooksAndAuthor('author-id-2');
Expected:
    Waiting 2s...
(sau 2 giây thì in ra)
fetchAllBook
fetchAuthorById

============================================
async function fetchAllBook() {
    await new Promise(resolve => {
        console.log('Waiting 2s...');
        setTimeout(() => resolve(), 2000);
    });
    console.log('fetchAllBook');
    return [
        {
            id: 'book-id-1',
            authorId: 'author-id-1'
        }, {
            id: 'book-id-2',
            authorId: 'author-id-2'
        }, {
            id: 'book-id-3',
            authorId: 'author-id-3'
        }
    ];
}

async function fetchAuthorById(authorId: string) {
    console.log('fetchAuthorById');
    return {
        authorId,
    };
}

// Too Sequential fixed
async function getBooksAndAuthorFixed(authorId: string) {
    const bookPromise = fetchAllBook();
    const authorPromise = fetchAuthorById(authorId);
    const books = await bookPromise;
    const author = await authorPromise;
    return {
        author,
        books: books.filter(book => book.authorId === authorId),
    };
}

getBooksAndAuthorFixed('author-id-2');
Expected:
    Waiting 2s...
fetchAuthorById
(2 giây sau in ra)
fetchAllBook

Mã nguồn tham khảo: https://github.com/codegym-vn/typescript-demo/tree/master/src

Trên đây CodeGym đã cùng với bạn luyện tập về Promise. Hãy chụp ảnh màn hình và nộp bài thực hành của bạn trên CodeGymX để cùng nhau luyện tập nhé!

Download - Giáo trình thuật toán

10 + 5 =

Tags:

0 Lời bình

Gửi Lời bình

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

BÀI VIẾT LIÊN QUAN

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY

098 953 44 58

Đăng ký tư vấn lộ trình học lập trình

Đăng ký tư vấn, định hướng lộ trình học và giải đáp các thắc mắc về ngành nghề – Miễn phí – Online.

12 + 5 =

TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM
TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM