What's new

Litong lito na ako sa promise ni javascript hayss

elbawonknu

Forum Guru
Elite
Joined
Dec 9, 2018
Posts
3,730
Solutions
1
Reaction
1,319
Points
1,519
Age
23
so ito naka gawa na ako weatherforecast website...bali ajax sa pag retrieve ng data ng api gamit ko kasi nag aral ako ng jquery nun tapos ayun pagkatapos ng project na yun plano ko aralan is reactjs...tapos nasabi sa isang vid na maganda mag react js kung napagaralan na mga mahahalagang concept ng js yung iba loop etc napagaralan ko na tapos nabasa ko dun yung promise ayun nag try ako pag aralan yun ewan ko ba litong lito ako kung paano sya nag gagana...napapagana ko sya pero hirap i seekin sa utak kung paano sya nagana
 
Hi! That's great that you've already built a weather forecast website using AJAX to retrieve data from an API. It's also good to hear that you're planning to learn ReactJS next.

Promises in JavaScript can be a bit tricky to understand at first, but once you get the hang of them, they can be very powerful for handling asynchronous operations. Think of promises as a way to handle something that will be completed in the future, like fetching data from an API.

Here's a simple breakdown of how promises work:

1. Creating a Promise: When you make an asynchronous call, such as fetching data from an API, you create a promise object. This object represents the eventual completion or failure of the asynchronous operation.

2. Pending, Fulfilled, Rejected: A promise can be in one of three states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed).

3. Handling a Promise: You can handle promises using .then() and .catch() methods.
- .then() is used to handle the result of a successful operation.
- .catch() is used to handle errors if the operation fails.

4. Chaining Promises: You can chain multiple promises together using .then() to handle sequential asynchronous operations.

5. Async/Await: Another way to work with promises is using the async and await keywords. async is used to define an asynchronous function, and await is used to wait for the promise to resolve.

Here's a simple example of using promises in JavaScript:

JavaScript:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const data = { message: 'Data fetched successfully' };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise
fetchData()
    .then((data) => {
        console.log(data.message);
    })
    .catch((error) => {
        console.error('Error fetching data:', error);
    });

I hope this explanation helps you understand how promises work in JavaScript. Feel free to ask if you have any specific questions or need further clarification!
 
Hi! That's great that you've already built a weather forecast website using AJAX to retrieve data from an API. It's also good to hear that you're planning to learn ReactJS next.

Promises in JavaScript can be a bit tricky to understand at first, but once you get the hang of them, they can be very powerful for handling asynchronous operations. Think of promises as a way to handle something that will be completed in the future, like fetching data from an API.

Here's a simple breakdown of how promises work:

1. Creating a Promise: When you make an asynchronous call, such as fetching data from an API, you create a promise object. This object represents the eventual completion or failure of the asynchronous operation.

2. Pending, Fulfilled, Rejected: A promise can be in one of three states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed).

3. Handling a Promise: You can handle promises using .then() and .catch() methods.
- .then() is used to handle the result of a successful operation.
- .catch() is used to handle errors if the operation fails.

4. Chaining Promises: You can chain multiple promises together using .then() to handle sequential asynchronous operations.

5. Async/Await: Another way to work with promises is using the async and await keywords. async is used to define an asynchronous function, and await is used to wait for the promise to resolve.

Here's a simple example of using promises in JavaScript:

JavaScript:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const data = { message: 'Data fetched successfully' };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise
fetchData()
    .then((data) => {
        console.log(data.message);
    })
    .catch((error) => {
        console.error('Error fetching data:', error);
    });

I hope this explanation helps you understand how promises work in JavaScript. Feel free to ask if you have any specific questions or need further clarification!
Code:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const data = { message: 'Data fetched successfully' };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise
fetchData()
    .then((data) => {
        console.log(data.message);
    })
    .catch((error) => {
        console.error('Error fetching data:', error);
    });

halimbawa nag fetch ako ng api tapos yung na recieve ko akala ko idadaan pa yun sa if else statement kung status 200 yung binigay ni api
 
Code:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const data = { message: 'Data fetched successfully' };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise
fetchData()
    .then((data) => {
        console.log(data.message);
    })
    .catch((error) => {
        console.error('Error fetching data:', error);
    });

halimbawa nag fetch ako ng api tapos yung na recieve ko akala ko idadaan pa yun sa if else statement kung status 200 yung binigay ni api
Sa iyong scenario, kung ang gusto mong i-check ang status code ng API response (halimbawa kung 200 o hindi), maaari kang magdagdag ng karagdagang pag-handle sa loob ng .then() block para suriin ito. Narito ang isang halimbawa ng kung paano mo maaring gawin ito:

JavaScript:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const fakeStatus = 200; // Simulated status code
            const data = { message: 'Data fetched successfully', status: fakeStatus };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise
fetchData()
    .then((data) => {
        if (data.status === 200) {
            console.log('API call successful!');
            console.log(data.message);
        } else {
            console.error('API call failed with status:', data.status);
        }
    })
    .catch((error) => {
        console.error('Error fetching data:', error);
    });

Sa code na ito, sa loob ng .then() block, inilalagay natin ang kondisyon para suriin ang status code na nakuha mula sa API response. Kung ang status ay 200, ipapakita natin sa console na ang API call ay matagumpay. Kung hindi, ipapakita natin ang mensahe na ang API call ay nabigo kasama ang status code.

Ganito ang isang paraan kung paano mo maaaring isama ang pag-check ng status code sa iyong pag-handle ng promise response. Sana makatulong ito sa iyong pag-unawa sa paggamit ng promises sa JavaScript! Kung may iba kang mga katanungan, huwag kang mag-atubiling magtanong.
 
Sa iyong scenario, kung ang gusto mong i-check ang status code ng API response (halimbawa kung 200 o hindi), maaari kang magdagdag ng karagdagang pag-handle sa loob ng .then() block para suriin ito. Narito ang isang halimbawa ng kung paano mo maaring gawin ito:

JavaScript:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const fakeStatus = 200; // Simulated status code
            const data = { message: 'Data fetched successfully', status: fakeStatus };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise
fetchData()
    .then((data) => {
        if (data.status === 200) {
            console.log('API call successful!');
            console.log(data.message);
        } else {
            console.error('API call failed with status:', data.status);
        }
    })
    .catch((error) => {
        console.error('Error fetching data:', error);
    });

Sa code na ito, sa loob ng .then() block, inilalagay natin ang kondisyon para suriin ang status code na nakuha mula sa API response. Kung ang status ay 200, ipapakita natin sa console na ang API call ay matagumpay. Kung hindi, ipapakita natin ang mensahe na ang API call ay nabigo kasama ang status code.

Ganito ang isang paraan kung paano mo maaaring isama ang pag-check ng status code sa iyong pag-handle ng promise response. Sana makatulong ito sa iyong pag-unawa sa paggamit ng promises sa JavaScript! Kung may iba kang mga katanungan, huwag kang mag-atubiling magtanong.
kahit yata wala ng catch diba kasi pag hindi na status 200 mag console error na sya?
 
kahit yata wala ng catch diba kasi pag hindi na status 200 mag console error na sya?
Tama ka, kung ikaw ay sigurado na ang iyong API call ay magkakaroon ng response status code 200 kung ito ay matagumpay at iba pang status code kung ito ay nabigo, maaari mong hindi na isama ang .catch() block sa iyong promise handling. Sa ganitong paraan, kung ang iyong API call ay hindi nagbalik ng status code na 200, ito ay iha-handle sa pamamagitan ng pagtawag sa .then() block na mayroong kondisyon para sa mga hindi inaasahang status code.

Narito ang isang halimbawa kung paano mo maaaring ito gawin:

JavaScript:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const fakeStatus = 404; // Simulated non-200 status code
            const data = { message: 'Data fetched successfully', status: fakeStatus };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise without catch block
fetchData()
    .then((data) => {
        if (data.status === 200) {
            console.log('API call successful!');
            console.log(data.message);
        } else {
            console.error('API call failed with status:', data.status);
        }
    });

Sa code na ito, hindi na natin isinama ang .catch() block. Kung ang status code na nakuha mula sa API response ay hindi 200, ito ay masasalamin sa pag-handle sa loob ng .then() block. Ang mensahe ng error ay maipapakita sa console basta't ang status code ay hindi 200.

Sana makatulong ito sa iyong pang-unawa sa pag-handle ng promises sa JavaScript. Kung mayroon ka pang ibang katanungan, huwag kang mag-atubiling magtanong!
 
Tama ka, kung ikaw ay sigurado na ang iyong API call ay magkakaroon ng response status code 200 kung ito ay matagumpay at iba pang status code kung ito ay nabigo, maaari mong hindi na isama ang .catch() block sa iyong promise handling. Sa ganitong paraan, kung ang iyong API call ay hindi nagbalik ng status code na 200, ito ay iha-handle sa pamamagitan ng pagtawag sa .then() block na mayroong kondisyon para sa mga hindi inaasahang status code.

Narito ang isang halimbawa kung paano mo maaaring ito gawin:

JavaScript:
function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate fetching data from an API
        setTimeout(() => {
            const fakeStatus = 404; // Simulated non-200 status code
            const data = { message: 'Data fetched successfully', status: fakeStatus };
            resolve(data); // Resolve the promise with the data
        }, 2000);
    });
}

// Using the promise without catch block
fetchData()
    .then((data) => {
        if (data.status === 200) {
            console.log('API call successful!');
            console.log(data.message);
        } else {
            console.error('API call failed with status:', data.status);
        }
    });

Sa code na ito, hindi na natin isinama ang .catch() block. Kung ang status code na nakuha mula sa API response ay hindi 200, ito ay masasalamin sa pag-handle sa loob ng .then() block. Ang mensahe ng error ay maipapakita sa console basta't ang status code ay hindi 200.

Sana makatulong ito sa iyong pang-unawa sa pag-handle ng promises sa JavaScript. Kung mayroon ka pang ibang katanungan, huwag kang mag-atubiling magtanong!
paano naman kung hindi sa pag fetch ng api kundi mag simulate lang ng promise?
 
paano naman kung hindi sa pag fetch ng api kundi mag simulate lang ng promise?
Kung gusto mong mag-simulate ng isang promise nang hindi tunay na nagfe-fetch mula sa isang API, maaari kang gumawa ng isang simpleng function na gumagawa ng promise na nagre-resolve pagkatapos ng ilang oras. Narito ang isang halimbawa:

JavaScript:
function simulatePromise() {
    return new Promise((resolve, reject) => {
        // Simulate asynchronous operation
        setTimeout(() => {
            const randomNum = Math.random();
            if (randomNum >= 0.5) {
                resolve('Success! Random number generated: ' + randomNum);
            } else {
                reject('Error! Random number generated: ' + randomNum);
            }
        }, 2000); // Simulated 2-second delay
    });
}

// Using the simulated promise
simulatePromise()
    .then((message) => {
        console.log(message);
    })
    .catch((error) => {
        console.error(error);
    });

Sa code na ito, ang simulatePromise function ay gumagawa ng isang promise na nagre-resolve pagkatapos ng 2 segundo. Ang resolve o reject ay depende sa random number na ginagawa sa loob ng function.

Sa paggamit ng promise na ito, maaari mong tawagin ang simulatePromise function at i-handle ang resolved o rejected promise gamit ang .then() at .catch() blocks.

Nawa'y makatulong ito sa iyong pag-unawa kung paano magsimula ng isang simulated promise sa JavaScript. Kung mayroon kang iba pang mga katanungan o kailangan ng karagdagang paliwanag, huwag kang mag-atubiling magtanong!
 
mag async kanalang 😅, madali lng ang concept.
Async means blocking, mag wait ka sa API bago mag execute ang dulo. Mag "try catch" ka din same sa promise.then() promise.catch()
 
Last edited:
mag async kanalang 😅, madali lng ang concept.
Async means blocking, mag wait ka sa API bago mag execute ang dulo. Mag "try catch" ka din same sa promise.then() promise.catch()
ano po pala main purpose ng setimeout sa promise?

napasok sa isip ko kasi lalo na pag nag retrieve ka ng marami or malaking file via api naka settimeout sya para mabigyan ng oras para maretrieve lahat ng files at i display ito pag na abot na yung oras...kung baga nag running na sya in a background yung function tapos mag retrieve ng file tapps pag successful at halimbawa completo yung file mag babalik ng stat 200 tapos pag hindi successful mag eeror sya? tama ba? medyo di ko pa gets kasi consepto ni promise
 
ano po pala main purpose ng setimeout sa promise?

napasok sa isip ko kasi lalo na pag nag retrieve ka ng marami or malaking file via api naka settimeout sya para mabigyan ng oras para maretrieve lahat ng files at i display ito pag na abot na yung oras...kung baga nag running na sya in a background yung function tapos mag retrieve ng file tapps pag successful at halimbawa completo yung file mag babalik ng stat 200 tapos pag hindi successful mag eeror sya? tama ba? medyo di ko pa gets kasi consepto ni promise
Promise is variable sya, na mag return ng value in the future, it can be success (with data) or fail (with error data).
Nag exist si variable Promise kasi imagine mo yung website lahat ang code is blocking (e wait niya ang every API request or delay request bago lumabas ang display (css, html, javascript, etc.)), diba parang supper lag at grabi ka nonesense yung paraan.
Ang Promise execution is naka parallel kasi or tinatawag na Asynchronous, separate sila sa normal code mo so mag expect ka na e priority yung normal code kaysa Promise.
Sa mga example dyan na setTimeout(), ito yung pinaka basic example na Promise Execution, like for example fully done executed na yung normal code pero merong naiwan na setTimeout() so later pa sya ma execute.
Same scenario din si API, it takes time mag execute si API like 3-15 seconds so mag expect ka na Promise yung ilalabas.
 

Similar threads

Back
Top