<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ankita</title>
    <description>The latest articles on DEV Community by Ankita (@ahana001).</description>
    <link>https://dev.to/ahana001</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F886127%2F00fdbfde-cfd2-4f53-9096-f7b97a64ee46.jpeg</url>
      <title>DEV Community: Ankita</title>
      <link>https://dev.to/ahana001</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ahana001"/>
    <language>en</language>
    <item>
      <title>SELECT FOR UPDATE and its behavior with foreign keys in PostgreSQL.</title>
      <dc:creator>Ankita</dc:creator>
      <pubDate>Sat, 22 Oct 2022 08:42:15 +0000</pubDate>
      <link>https://dev.to/ahana001/select-for-update-and-its-behavior-with-foreign-keys-in-postgresql-kpe</link>
      <guid>https://dev.to/ahana001/select-for-update-and-its-behavior-with-foreign-keys-in-postgresql-kpe</guid>
      <description>&lt;p&gt;The general approach followed by developers is to pre-acquire the lock(FOR UPDATE)on the data sets that are being updated/deleted concurrently. &lt;/p&gt;

&lt;p&gt;This approach may be considered to solve concurrency problems occurs due to concurrently running transactions. if you are confused that &lt;strong&gt;what is concurrency problems?&lt;/strong&gt; then check out my blog &lt;a href="https://dev.to/ahana001/concurrency-problems-3dga"&gt;concurrency in dbms&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To start with a simple scenario, let us consider the following example with two tables and let us assume that an application is running concurrent update operations on the parent table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
CREATE TABLE parent(id INT PRIMARY KEY, balance INT);

CREATE TABLE child(id INT REFERENCES parent(id) ON DELETE CASCADE, trx_timestamp TIMESTAMP);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.&lt;/p&gt;

&lt;p&gt;ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.&lt;/p&gt;

&lt;p&gt;Let's Insert some data in both table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO parent VALUES (1,1000),(2,2000),(3,3000) ;

INSERT INTO child VALUES( 1 ,now()),( 2 ,now());

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following is an example transaction on the parent table which is using the FOR UPDATE clause to avoid any deadlock problems for this specific transaction.&lt;/p&gt;

&lt;p&gt;Now, consider that I have an another concurrent transaction which tries to insert the data into the child table.&lt;/p&gt;

&lt;p&gt;Following is the behaviour observed,  when we run these two transactions concurrently.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MPY0eJ15--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/du03qvd75ql321nz50n4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MPY0eJ15--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/du03qvd75ql321nz50n4.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you see in the above output, the insert operation on the child table is in waiting state.&lt;br&gt;
Even though the FOR UPDATE clause does not exist in the SESSION 2, the transaction would still remain in a waiting state. The reason for this waiting state is due to the PostgreSQL's FOREIGN KEY data validation process between the child and parent tables.&lt;/p&gt;

&lt;p&gt;By default, when we use FOR UPDATE, it means that it is going to return the rows which are retrieved by the select statement by acquiring the lock on key columns.&lt;/p&gt;

&lt;p&gt;In the above example we are actually updating the non key column(balance), by acquiring the lock on id column.&lt;/p&gt;

&lt;p&gt;As we hold the lock on primary key column id, when we try to insert any value into the child table, then it will&lt;br&gt;
try to acquire the SHARE lock on the parent table's id column. In this case, the SESSION 2 transaction will wait until the SESSION 1 transaction is complete.&lt;/p&gt;

&lt;p&gt;In majority of the cases, we actually do not need to update any key columns,&lt;br&gt;
rather we update only the non key columns like salary, phone number, address, etc. While updating the non key column values, we could force the behavior to not hold any lock on the key columns. To achieve this with SELECT FOR UPDATE in PostgreSQL, we could use the NO KEY option in the FOR UPDATE clause.&lt;/p&gt;

&lt;p&gt;Now, let try the same example with the NO KEY option.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NmE6WJyA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyz3glr6p6k6pa7dlcz1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NmE6WJyA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyz3glr6p6k6pa7dlcz1.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;successfully inserted row in child table.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>concurrency problems</title>
      <dc:creator>Ankita</dc:creator>
      <pubDate>Sat, 22 Oct 2022 06:51:15 +0000</pubDate>
      <link>https://dev.to/ahana001/concurrency-problems-3dga</link>
      <guid>https://dev.to/ahana001/concurrency-problems-3dga</guid>
      <description>&lt;p&gt;When multiple transactions execute concurrently in an uncontrolled or unrestricted manner, then it might lead to several problems.&lt;/p&gt;

&lt;p&gt;Such problems are called as &lt;strong&gt;concurrency problems&lt;/strong&gt;.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Dirty Read Problem&lt;/li&gt;
&lt;li&gt;Unrepeatable Read Problem&lt;/li&gt;
&lt;li&gt;Lost Update Problem&lt;/li&gt;
&lt;li&gt;Phantom Read Problem&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Dirty Read Problem
&lt;/h3&gt;

&lt;p&gt;Reading the data written by an uncommitted transaction is called as dirty read. &lt;/p&gt;

&lt;p&gt;This read is called as dirty read because there is always a chance that the uncommitted transaction might roll back later.Thus, uncommitted transaction might make other transactions read a value that does not even exist.This leads to inconsistency of the database. &lt;/p&gt;

&lt;p&gt;Dirty read does not lead to inconsistency always.It becomes problematic only when the uncommitted transaction fails and roll backs later due to some reason.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0S-aoXFz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sg682gx5usv6qy3o9eng.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0S-aoXFz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sg682gx5usv6qy3o9eng.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Unrepeatable Read Problem
&lt;/h3&gt;

&lt;p&gt;This problem occurs when a transaction read different values of the same variable in its different read operations even when it has not updated its value.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_lC3wnt1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7rsm0pldmkga84yyvwwf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_lC3wnt1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7rsm0pldmkga84yyvwwf.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Lost Update Problem
&lt;/h3&gt;

&lt;p&gt;This problem occurs when multiple transactions execute concurrently and updates from one or more transactions get lost.&lt;/p&gt;

&lt;p&gt;This problem occurs whenever there is a write-write conflict.In write-write conflict, there are two writes one by each transaction on the same data item without any read in the middle.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Wh1up0CM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf7cl5rqholsdwimwo3l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Wh1up0CM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf7cl5rqholsdwimwo3l.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Phantom Read Problem
&lt;/h3&gt;

&lt;p&gt;This problem occurs when a transaction reads some variable from the buffer and when it reads the same variable later, it finds that the variable does not exist.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Hzz0_2ZD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8kpgexfyn2z2z1dffvpd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Hzz0_2ZD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8kpgexfyn2z2z1dffvpd.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>ERROR #1093 : You can't specify target table table_name for update in FROM clause</title>
      <dc:creator>Ankita</dc:creator>
      <pubDate>Sat, 16 Jul 2022 17:28:09 +0000</pubDate>
      <link>https://dev.to/ahana001/error-1093-you-cant-specify-target-table-tablename-for-update-in-from-clause-2j2n</link>
      <guid>https://dev.to/ahana001/error-1093-you-cant-specify-target-table-tablename-for-update-in-from-clause-2j2n</guid>
      <description>&lt;p&gt;In this blog, we will solve one MySQL question and understand errors while solving the problem.&lt;/p&gt;

&lt;p&gt;Problem : &lt;br&gt;
Delete Duplicate Emails&lt;/p&gt;

&lt;p&gt;Table: Person&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| email       | varchar |
+-------------+---------+


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;id is the primary key column for this table.&lt;br&gt;
Each row of this table contains an email. The emails will not contain uppercase letters.&lt;/p&gt;

&lt;p&gt;Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id.&lt;/p&gt;

&lt;p&gt;Input: &lt;br&gt;
Person table:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

+----+------------------+
| id | email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

+----+------------------+
| id | email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Explanation: &lt;a href="mailto:john@example.com"&gt;john@example.com&lt;/a&gt; is repeated two times. We keep the row with the smallest Id = 1.&lt;/p&gt;

&lt;p&gt;If We want No. of count which is having same email then we should use GROUP BY method.&lt;/p&gt;

&lt;p&gt;The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of id in each email".&lt;/p&gt;

&lt;p&gt;The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwq7hz5y4fd044uleocda.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwq7hz5y4fd044uleocda.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we group each row that has the same email and find a count of the row with COUNT() function. email &lt;a href="mailto:john@example.com"&gt;john@example.com&lt;/a&gt; occurs two times so we get a count as 2 and for &lt;a href="mailto:bob@example.com"&gt;bob@example.com&lt;/a&gt; we get a count as 1 because it occurs only one time. &lt;/p&gt;

&lt;p&gt;Here email &lt;a href="mailto:john@example.com"&gt;john@example.com&lt;/a&gt; has two ids 1 and 3. If We want to get minimum id from these two ids or minimum id from any no. of ids for particular email then we have to use MIN() function.&lt;/p&gt;

&lt;p&gt;MySQL query should be like : &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6jlqm6xsk29g53xu341h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6jlqm6xsk29g53xu341h.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we get id 1 for email &lt;a href="mailto:john@example.com"&gt;john@example.com&lt;/a&gt; because min(1,3) should be 1 and get 2 for &lt;a href="mailto:bob@example.com"&gt;bob@example.com&lt;/a&gt; because it has only one id that should be returned in MIN() function.&lt;/p&gt;

&lt;p&gt;Now we have completed our major task in this problem. We want only id that is not in this min id because we want to keep the smallest id in our table and delete all ids that are greater than small id which has same email. so we first group row that has same email and then finds the smallest id from that to keep smallest id in table and delete all the row that has same email with id &amp;gt; small(id).&lt;/p&gt;

&lt;p&gt;so the query will delete all id that is not equal to smallest id of particular email.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx5vs9lxnupoclq4zfi3v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx5vs9lxnupoclq4zfi3v.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Oops...&lt;br&gt;
We have got an Error. &lt;/p&gt;

&lt;p&gt;ERROR #1093 : You can't specify the target table table_name for an update in FROM clause&lt;/p&gt;

&lt;p&gt;What you can do is change the query to something like this below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2lctnpg5rmgx1ndbl3ue.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2lctnpg5rmgx1ndbl3ue.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Okay, let me explain how the magic happens here.&lt;/p&gt;

&lt;p&gt;You can not delete the rows from the same data source to which your sub-query refers. This above-mentioned query is a working, but it’s ugly for several reasons, including performance. Here nested subquery makes a temporary table. So it doesn’t count as the same table you’re trying to delete data from. &lt;/p&gt;

&lt;p&gt;This is because your update could be cyclical. what if updating that record causes something to happen which made the WHERE condition FALSE? You know that isn’t the case, but the engine doesn’t. There also could be opposing locks on the table in the operation.&lt;/p&gt;

</description>
      <category>mysql</category>
    </item>
    <item>
      <title>Trust Issues with setTimeout()</title>
      <dc:creator>Ankita</dc:creator>
      <pubDate>Sun, 03 Jul 2022 13:22:02 +0000</pubDate>
      <link>https://dev.to/ahana001/trust-issues-with-settimeout-43pb</link>
      <guid>https://dev.to/ahana001/trust-issues-with-settimeout-43pb</guid>
      <description>&lt;p&gt;what is setTimeout()?&lt;br&gt;
Special asynchronous functions like setTimeout, setInterval are provided to JS by the environment it is currently running on. For example in case of Chrome JavaScript runs on the V8 engine, and Fire Fox uses SpiderMonkey as its JavaScript engine etc.&lt;/p&gt;

&lt;p&gt;The setTimeout() method calls a function after a number of milliseconds. It sets a timer which executes a function or specified piece of code once the timer expires.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZgOG1hA0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uswv6h4mijttc4ftk6jd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZgOG1hA0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uswv6h4mijttc4ftk6jd.png" alt="Image description" width="880" height="397"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  setTimeout with delay of 5000 milliseconds does not always wait for exactly 5000 milliseconds. There are trust issues.
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--L8ceK20b--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqpghzhbyr9qc6ri3e7n.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--L8ceK20b--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqpghzhbyr9qc6ri3e7n.jpg" alt="Image description" width="180" height="180"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's take one example and make it clear:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1Ipl52hz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ue6n6aas6obpjyrqj8zd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1Ipl52hz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ue6n6aas6obpjyrqj8zd.png" alt="Image description" width="880" height="659"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;JavaScript is single threaded. Every line of code goes into call stack and gets executed.&lt;/p&gt;

&lt;p&gt;date.getTime() method return current time in milliseconds. so I note the time when the execution of the program starts. our JS makes a timer for callback function of setTimeout and execution goes to the next line. &lt;/p&gt;

&lt;p&gt;Here we use for loop to make more time in execution of our synchronous code. so when the call stack is busy in the execution of for loop our sweet timer gets expires but our call stack is busy in for loop so does execute callback function. our callback function is waiting in queue.&lt;/p&gt;

&lt;p&gt;When the call stack finishes its loop execution it immediately runs our callback function. In the callback function, we get that time in milliseconds and log the total time of execution which may be greater than our delay time. &lt;/p&gt;

&lt;p&gt;How much time setTimout takes, it's all dependence on our execution stack.   &lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>How to use API with Fetch API and Promises.</title>
      <dc:creator>Ankita</dc:creator>
      <pubDate>Sun, 03 Jul 2022 06:04:33 +0000</pubDate>
      <link>https://dev.to/ahana001/how-to-use-api-with-fetch-api-and-promises-5hh3</link>
      <guid>https://dev.to/ahana001/how-to-use-api-with-fetch-api-and-promises-5hh3</guid>
      <description>&lt;p&gt;A big part of working with JavaScript is learning how to connect to the API. As a new developer, at times you may just be asked to "play with some APIs"! To learn what they are and how to work with them. We're going to make a very simple advice generator web app with plain JavaScript that will retrieve information from an API and display it on the page.&lt;/p&gt;

&lt;h2&gt;
  
  
  PREREQUISITES
&lt;/h2&gt;

&lt;p&gt;Basic knowledge of HTML and CSS.&lt;br&gt;
Basic knowledge of JavaScript syntax and datatypes.&lt;br&gt;
Basic knowledge of working with JSON and JavaScript objects.&lt;/p&gt;

&lt;h2&gt;
  
  
  GOALS
&lt;/h2&gt;

&lt;p&gt;We are going to write from scratch random advice generator app that connects to &lt;a href="https://api.adviceslip.com/"&gt;Advice Slip API&lt;/a&gt;, retrieves the data with JavaScript, and displays it on the front end of a website.&lt;/p&gt;

&lt;p&gt;It will look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4MpM0qXw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snumqdnh0rmusai7lfo8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4MpM0qXw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snumqdnh0rmusai7lfo8.jpg" alt="Image description" width="880" height="645"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Quick overview:
&lt;/h2&gt;

&lt;p&gt;What is an API?&lt;br&gt;
APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. An API is simply a medium to talk to program. For example, the weather bureau’s software system contains daily weather data. The weather app on your phone “talks” to this system via APIs and shows you daily weather updates on your phone.&lt;/p&gt;

&lt;p&gt;Let's make it more clear with our vanilla JS DOM Element Example:&lt;br&gt;
If You want HTML Elements in the JavaScript world you tell the browser to give that elements but how the browser will understand your language? it is done by using the querySelector API. Using document.querySelector API you can talk with the browser to give that particular element to me so I can make changes in it.&lt;/p&gt;

&lt;p&gt;What is HTTP Request?&lt;br&gt;
HTTP Requests are messages which are sent by the client or user to initiate an action on the server. HTTP works as a request-response protocol between a client and server.&lt;/p&gt;

&lt;p&gt;Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.&lt;/p&gt;

&lt;p&gt;You may be familiar with the concept of a CRUD app, which stands for Create, Read, Update, Delete. Any programming language can be used to make a CRUD app with various methods. A web API uses HTTP requests that correspond to the CRUD verbs.&lt;/p&gt;

&lt;p&gt;HTTP Method : POST      =&amp;gt; Creates a new resource&lt;br&gt;
HTTP Method : GET       =&amp;gt; Retrieves a resource&lt;br&gt;
HTTP Method : PUT/PATCH =&amp;gt; Updates an existing resource&lt;br&gt;
HTTP Method : DELETE    =&amp;gt; Deletes a resource&lt;/p&gt;

&lt;p&gt;Let's get started.&lt;br&gt;
We want to read data from our &lt;a href="https://api.adviceslip.com/"&gt;Advice Slip API&lt;/a&gt; so we are going to use HTTP GET method.&lt;/p&gt;

&lt;p&gt;Let’s begin by creating a index.html file that contains some basic information, in order to render a page.&lt;/p&gt;

&lt;p&gt;If I open this index.html page, I should see black page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LrEsTh3S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xpbsyjwtimqy13prp193.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LrEsTh3S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xpbsyjwtimqy13prp193.png" alt="basic Index.html" width="880" height="455"&gt;&lt;/a&gt;&lt;br&gt;
Let’s now create our index.js file, which is referenced inside our html file.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WfCmpxTA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4r5nfjg2ih0ckanhp8of.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WfCmpxTA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4r5nfjg2ih0ckanhp8of.png" alt="how to referenced index.js file inside index.html" width="880" height="303"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Inside our index.js file fetch data from the advice slip API and log the response&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pPAeXGIy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4hm26gvsqkxwxg1lwxd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pPAeXGIy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4hm26gvsqkxwxg1lwxd.png" alt="fetching data from api" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is Fetch API?&lt;br&gt;
The Fetch API is a simple interface for fetching resources. Fetch allows us to make network request and handle responses easier than our old friend XMLHttpRequest(XHR). One of the main differences is that Fetch API uses Promises.&lt;/p&gt;

&lt;p&gt;The fetch function takes one mandatory argument, which is the path to the resource you want to fetch and returns a Promise that resolves to the Response of that request.&lt;/p&gt;

&lt;p&gt;What is Promise?&lt;br&gt;
A JavaScript Promise object can be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Pending&lt;/li&gt;
&lt;li&gt;Fulfilled&lt;/li&gt;
&lt;li&gt;Rejected&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Promise object supports two properties: state and result.&lt;/p&gt;

&lt;p&gt;While a Promise object is "pending" (working), the result is undefined.&lt;br&gt;
When a Promise object is "fulfilled", the result is a value.&lt;br&gt;
When a Promise object is "rejected", the result is an error object.&lt;/p&gt;

&lt;p&gt;When making an HTTP request as an asynchronous operation, fetch will not return any data. However it will return a response promise. When we log the response, it will show this Promise is in pending state. This means that the HTTP response we are expecting will get back eventually, but at the time of logging, this response was not ready to be logged.&lt;/p&gt;

&lt;p&gt;Our Promise is in pending state, it can now transition into a fulfilled state if everything goes well or a rejected state if there’s an error while fetching. Once the Promise is settled, it can’t no longer change state.&lt;/p&gt;

&lt;p&gt;Let’s now move back to our example and learn on how we can extract some data from this response Promise object. We will use the Promise.prototype.then method in order to attach a callback once our Promise has been fulfilled.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--uFMvxNXJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zp3smm0cri46prvanoe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uFMvxNXJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zp3smm0cri46prvanoe.png" alt="Image description" width="880" height="333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7S_bL4By--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5e2k8ahz8ww9cztp99k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7S_bL4By--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5e2k8ahz8ww9cztp99k.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we know our API response is working, we want to move on and actually get the body of the response. We want to call the json() method on the response in order to get the response body in json format. This operation is also asynchronous. The json() method actually returns a Promise, so we will need to create a Promise chain.&lt;/p&gt;

&lt;p&gt;We will pass the value we receive from the first Promise into our chain in order to do some operations. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zdhsu2wy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwyrnga444fgmb2mw328.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zdhsu2wy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwyrnga444fgmb2mw328.png" alt="Image description" width="880" height="342"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you refresh your browser and check your logs, you will see a object with key that contain attributes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7B9jqci2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h119bdj8fwnei4itu6cx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7B9jqci2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h119bdj8fwnei4itu6cx.png" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we can add it to our html element and get advice in front end.&lt;br&gt;
we have used window.onload it is used to launch certain functions whenever a web page is loaded. Here we are loading advice when web page is loaded.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vv4xvsIY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80b4f1tqdt1mqe3d7biq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vv4xvsIY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80b4f1tqdt1mqe3d7biq.png" alt="Image description" width="880" height="724"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EkQ27dxV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/642pdtxom0ny6s6af70n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EkQ27dxV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/642pdtxom0ny6s6af70n.png" alt="Image description" width="880" height="729"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>api</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
