<?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>Forem: Ruxin Qu</title>
    <description>The latest articles on Forem by Ruxin Qu (@rosiequ).</description>
    <link>https://forem.com/rosiequ</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%2F889318%2F25bd8f7b-18ce-4200-a58b-4e5b9ff44b47.jpeg</url>
      <title>Forem: Ruxin Qu</title>
      <link>https://forem.com/rosiequ</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rosiequ"/>
    <language>en</language>
    <item>
      <title>Wordpress: functions</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Wed, 20 Mar 2024 03:30:38 +0000</pubDate>
      <link>https://forem.com/rosiequ/wordpress-functions-32</link>
      <guid>https://forem.com/rosiequ/wordpress-functions-32</guid>
      <description>&lt;p&gt;To integrate links into WordPress, follow these steps:&lt;/p&gt;

&lt;p&gt;Begin by creating a &lt;code&gt;functions.php&lt;/code&gt; file within your WordPress theme directory. Within this file, define a function to enqueue external resources, ensuring that WordPress can load them as needed.&lt;/p&gt;

&lt;p&gt;Within the function, when incorporating a CSS library, utilize &lt;code&gt;wp_enqueue_style()&lt;/code&gt;. Within its parentheses, the first parameter serves as a descriptor, which can be any string. The second parameter is the URL link to the resource. Note that the link need not include 'https:' since, in some instances, HTTPS may not be available in local environments.&lt;/p&gt;

&lt;p&gt;If you intend to include a JavaScript library, employ &lt;code&gt;wp_enqueue_script()&lt;/code&gt;. This function accepts five parameters: the first is a descriptor, followed by the URL link to the script. Next is an array specifying any dependencies the script relies upon. Subsequently, indicate the version number, followed by a boolean value indicating whether the script should load after the page has fully loaded (set to true to ensure the JavaScript loads at the page's end).&lt;/p&gt;

&lt;p&gt;After defining the function, within the PHP code's conclusion, call the function using &lt;code&gt;add_action('wp_enqueue_scripts','functionName')&lt;/code&gt;. This ensures that the function is invoked when necessary.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>wordpress: the loop</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Wed, 13 Mar 2024 19:05:41 +0000</pubDate>
      <link>https://forem.com/rosiequ/wordpress-the-loop-4co5</link>
      <guid>https://forem.com/rosiequ/wordpress-the-loop-4co5</guid>
      <description>&lt;ol&gt;
&lt;li&gt;use Local for dev development. The theme files are saved in the path: &lt;code&gt;/Local Sites/site-name/app/public/wp-content/themes/theme-name&lt;/code&gt;/.&lt;/li&gt;
&lt;li&gt;index.php is normally used as a homepage that display all the posts and single.php displays the single post.&lt;/li&gt;
&lt;li&gt;php the loop:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while(have_posts()){
the_post() 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;the_post()&lt;/code&gt;function keeps track of the current post. &lt;br&gt;
When reaching the loop, Wordpress first determines if the page is single.php or not. If not, Wordpress retrieves multiple posts based on the requested criteria. If the loop is in the single.php page, Wordpress will only retrieve the current post.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;using html in php functions, use &lt;code&gt;?&amp;gt; &amp;lt;html here&amp;gt; &amp;lt;?php&lt;/code&gt; can display the post data retrieved from Wordpress database to the page. 
For example: &lt;code&gt;?&amp;gt;&amp;lt;h2&amp;gt;&amp;lt;?php the_title()?&amp;gt;&amp;lt;/h2&amp;gt;&amp;lt;?php&lt;/code&gt; displays the title of the post&lt;/li&gt;
&lt;li&gt;adding a new page: go to the admin and click 'add new page'. The url will be shown on page setting. Update the page template in page.php file.&lt;/li&gt;
&lt;li&gt;page.php displays the template that will apply to all pages except the home and single page. To do conditional rendering, use if statement. For example:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(is_page('test'){
?&amp;gt;&amp;lt;h1&amp;gt;This is a test page&amp;lt;/h1&amp;gt;&amp;lt;?php
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>JS array methods</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Sun, 25 Feb 2024 16:29:30 +0000</pubDate>
      <link>https://forem.com/rosiequ/js-array-methods-30j6</link>
      <guid>https://forem.com/rosiequ/js-array-methods-30j6</guid>
      <description>&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;array.split()&lt;/code&gt; turns a string into an array and returns the array
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const text = "I love doing web development";
const myArray = text.split(" ");
//output: [ 'I', 'love', 'doing', 'web', 'development' ]
const newArray = text.split("");
//output: [
  'I', ' ', 'l', 'o', 'v', 'e',
  ' ', 'd', 'o', 'i', 'n', 'g',
  ' ', 'w', 'e', 'b', ' ', 'd',
  'e', 'v', 'e', 'l', 'o', 'p',
  'm', 'e', 'n', 't'
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;array.slice()&lt;/code&gt; take a cut of the original array and return the cut part
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myArr = ['apple','pear','strawberry']
const cut = myArr.slice(0,1)
//output: 'apple' it slice between the zero index and the first index
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;string.slice()&lt;/code&gt; can also be used on a string. &lt;strong&gt;Note&lt;/strong&gt;: .slice doesn't change the original string or array. The cut includes the start and excludes the end
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myText="I have a golden retriever"
const cut = myText.slice(3,5)
//output: 'av' 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;array.splice()&lt;/code&gt; can be used to add/remove one or multiple elements in an array. &lt;strong&gt;Note&lt;/strong&gt;: it does change the original array&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;for removing element(s):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = ["I", "love", "doing", "web", "development"];
console.log(array.splice(0, 2));
//output: [ 'I', 'love' ]
console.log(array);
//output: [ 'doing', 'web', 'development' ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;for adding element(s):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;array.splice(0, 2, "hello");
console.log(array);
//output: [ 'hello', 'doing', 'web', 'development' ] it removes the elements between index 0 and 2 and adds the provided element to the 0th index
array.splice(5, 0, "very", "much", "!");
console.log(array);
//output: [ 'I', 'love', 'doing', 'web', 'development', 'very', 'much', '!' ] it found the 5th index and remove 0 element and add the provided elements to the 5th index
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>C#: Console and datatypes</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Thu, 09 Nov 2023 08:59:58 +0000</pubDate>
      <link>https://forem.com/rosiequ/i-started-learning-c-ioe</link>
      <guid>https://forem.com/rosiequ/i-started-learning-c-ioe</guid>
      <description>&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;Console.WriteLine("Hello World")&lt;/code&gt; prints the output on the existing line and appends a new line after it. &lt;code&gt;Console.Write("hello"); Console.Write("World");&lt;/code&gt; print in the same line&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.WriteLine()&lt;/code&gt; and &lt;code&gt;.Write()&lt;/code&gt; are both methods in the class &lt;code&gt;Console&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;comparison operators: &lt;code&gt;&amp;gt; &amp;lt; &amp;gt;= &amp;lt;=&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;equality and inequality operator: &lt;code&gt;== !==&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;logical negation operator: &lt;code&gt;!&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;declare a string : &lt;code&gt;string myString = "This is a string";&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;string method: &lt;code&gt;Contains(), StartsWith(), EndsWith(), ToLower(), ToUpper(), Trim()&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;A literal value is a constant value that never changes. There are 5 common literal data types.&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;character literals: one single alphanumeric character, &lt;code&gt;Console.WriteLine('b')&lt;/code&gt; single quotes create a &lt;code&gt;char&lt;/code&gt; literal and double quotes create a string literal&lt;/li&gt;
&lt;li&gt;integer literals: &lt;code&gt;int&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;floating-point number: &lt;code&gt;float&lt;/code&gt; append letter &lt;code&gt;F&lt;/code&gt; after the number,&lt;code&gt;double&lt;/code&gt; and &lt;code&gt;decimal&lt;/code&gt; add letter &lt;code&gt;m&lt;/code&gt; or &lt;code&gt;M&lt;/code&gt; will both work&lt;/li&gt;
&lt;li&gt;boolean&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;implicitly typed: &lt;code&gt;var&lt;/code&gt; (&lt;strong&gt;Note&lt;/strong&gt;: This doesn't equal to dynamically typed)&lt;/li&gt;
&lt;li&gt;Using template literals and string interpolation allows easy way to interpolate variables and expressions &lt;code&gt;Console.WriteLine($"Hello {firstName}!")&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>express-session &amp; cookie</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Wed, 16 Nov 2022 04:11:07 +0000</pubDate>
      <link>https://forem.com/rosiequ/express-session-cookie-1ee9</link>
      <guid>https://forem.com/rosiequ/express-session-cookie-1ee9</guid>
      <description>&lt;ol&gt;
&lt;li&gt;HTTP is stateless, after a response is sent, the client and the server will forgot about each other. Cookies and URL parameters can store data but it's readable to client side. Session can store data on the server side. When a session is created, an ID will be assigned to the user, and the further requests are made with the ID, so the server can recognize the user.&lt;/li&gt;
&lt;li&gt;A session middleware example. connect-session-sequelize package is used to store session data.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(
    session({
        secret: 'dahuang',
        cookie: { maxAge: 172800000, secure: false, sameSite: 'strict' },
        resave: false,
        saveUninitialized: false,
        store: new SequelizeStore({
            db: sequelize,
        })
    })
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3  &lt;a href="https://www.geeksforgeeks.org/difference-between-session-and-cookies/"&gt;The difference between session and cookie&lt;/a&gt;: Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over.&lt;/p&gt;

&lt;p&gt;4 To make it easy for client side to attach the session id onto every request, session id are saved in client side in cookies. Cookies are small pieces of data in key-value pairs. A session cookie is set with the first HTTP response from the server and persists until the browser is closed or cookie expires. Cookies are in HTTP header.&lt;/p&gt;

&lt;p&gt;5 The flow of how session is implemented with cookie:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- A user goes to a site(a request is sent), the server creates a session and a session id
- The server sends the session id back to browser in HTTP header, and the browser stores the session id in cookie
- The session cookie automatically attaches to all the following request to the server.
- The server receives the request sent with session id, it responses with the data associated with the ID. 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;6 passport.js is an authentication package. Here's example of passport local strategy with sequelize. In the server.js file, we need to initialize passport after the session middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(passport.initialize());
app.use(passport.session());

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

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;passport.use(
    new LocalStrategy(
        {
            usernameField: 'email',
            passwordField: 'password',
        },
        async (email, password, done) =&amp;gt; {
            try {
                const user = await User.findOne({ where: { email: email } });
                if (!user) {
                    return done(null, false, {
                        message: 'email not registered',
                    });
                }
                const matchPassword = await user.checkPassword(password);
                return matchPassword
                    ? done(null, user)
                    : done(null, false, { message: 'Incorrect password' });
            } catch (error) {
                done(error);
            }
        }
    )
);

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findByPk(id).then(function(user) { done(null, user); });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;SerializeUser: to persist user data into session. Here we saved the user id, eg: req.session.passport.user = 1.
DeserializeUser to get the user data from session, attach the user data to req as req.user. For more &lt;a href="https://stackoverflow.com/questions/27637609/understanding-passport-serialize-deserializ"&gt;detail&lt;/a&gt; about serialize and deserialize user.&lt;/li&gt;
&lt;li&gt;for passport middleware, it takes three params, username(or email), password, and a callback function done(), if there's error, return &lt;code&gt;done(error)&lt;/code&gt;, if no user is found, return &lt;code&gt;done(null, false)&lt;/code&gt;, null means no error. If the password doesn't match, return &lt;code&gt;done(null, false)&lt;/code&gt;. If the username and password both match the data from db, return &lt;code&gt;done(null, user)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>ORM : Sequelize</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Wed, 16 Nov 2022 00:57:15 +0000</pubDate>
      <link>https://forem.com/rosiequ/orm-sequelize-4do7</link>
      <guid>https://forem.com/rosiequ/orm-sequelize-4do7</guid>
      <description>&lt;ol&gt;
&lt;li&gt;Sequelize only provides ORM, to interact with a database, a database driver is still needed, like mysql2.&lt;/li&gt;
&lt;li&gt;In sequelize, database tables are referred as models. A model is an abstraction that represents a table in the database.&lt;/li&gt;
&lt;li&gt;To create a database connection, put the database name, username and password in an environment variable.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require('dotenv').config()
const {Sequelize} = require('sequelize')
sequelize = new Sequelize(
        process.env.DB_NAME,
        process.env.DB_USERNAME,
        process.env.DB_PASSWORD,
        {
            host: process.env.DB_HOST,
            dialect: 'mysql'
        }
    );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;4 To create an instance of Model, use &lt;code&gt;sequelize.define()&lt;/code&gt; or &lt;code&gt;class User extends Model&lt;/code&gt;. The instance can have method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { Model, DataTypes } = require('sequelize');
class User extends Model {
    async checkPassword(password) {
        try {
            const matchPassword = await bcrypt.compare(password, this.password);
            return matchPassword;
        } catch (err) { console.error(err); }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;5 By default, sequelize add createAt and updateAt columns, to prevent it use &lt;code&gt;timestamps: false&lt;/code&gt;. &lt;code&gt;freezeTableName: true&lt;/code&gt; will make the table name same with model name. &lt;/p&gt;

&lt;p&gt;6 &lt;code&gt;sequelize.sync({force: true})&lt;/code&gt; will synchronize the model to database. It creates a new table and drops the existing one first.&lt;/p&gt;

&lt;p&gt;7 Sequelize hooks are functions called before or after sequelize calls are executed. The code below will hash the password everytime before a new user is created and saved.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;hooks: {
    beforeCreate: async (userData) =&amp;gt; {
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(userData.password, salt);
        userData.password = hashedPassword;
    },
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;8 Populate the database: &lt;code&gt;model.create()&lt;/code&gt; or &lt;code&gt;model.bulkCreate()&lt;/code&gt;. &lt;code&gt;model.update()&lt;/code&gt; to update the data. &lt;code&gt;model.destroy()&lt;/code&gt; to delete the data.&lt;/p&gt;

&lt;p&gt;9 Three common types between tables: one to one, one to many and many to many.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One to One
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User.hasOne(Passport)
Passport.belongsTo(User)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;One to many
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User.hasMany(Post)
Post.belongsTo(User)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Many to many: The studentClass table will have three columns: id, student_id and class_id
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Student.belongsToMany(Class, {through: studentClass, foreighKey: student_id})
Class.belongsToMany(Student, {through: studentClass, foreignKey: class_id})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;10 &lt;code&gt;model.findAll()&lt;/code&gt; can find all the data in the mobel. It can be used with where clause and operators&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const postData = await Post.findAll(
    {
        where: { user_id: req.user.id },
        include: { model: User }
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;11 &lt;code&gt;model.findOne()&lt;/code&gt; will return the one matching data. It can include the data from other models.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const postData = await Post.findOne({
    where: { id: req.params.id },
        include: [
            { model: User },
            { 
                model: Comment,
                include: [User] // here is a join of comment and user table
            }]
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>JavaScript: Test with mocha</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Sat, 15 Oct 2022 20:36:53 +0000</pubDate>
      <link>https://forem.com/rosiequ/javascript-test-with-mocha-472j</link>
      <guid>https://forem.com/rosiequ/javascript-test-with-mocha-472j</guid>
      <description>&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;test suite&lt;/em&gt; is a collection of tests for a web application. To run a test suite, do &lt;code&gt;npm test&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;the test file for &lt;code&gt;index.js&lt;/code&gt; should be named as &lt;code&gt;index-test.js&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;testing types:

&lt;ul&gt;
&lt;li&gt;unit test: test the smallest unit of the code&lt;/li&gt;
&lt;li&gt;integration test: test the interaction between &lt;strong&gt;internal services&lt;/strong&gt; inside the web application&lt;/li&gt;
&lt;li&gt;End to End test: real user experience&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;test with mocha:

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;npm init -y&lt;/code&gt; to create a package.json file for managing packages.&lt;/li&gt;
&lt;li&gt;install mocha by &lt;code&gt;npm install mocha -D&lt;/code&gt; so it's saved under &lt;code&gt;devDependencies&lt;/code&gt; in package.json, which means it's only included during development mode not in the production bundle.&lt;/li&gt;
&lt;li&gt;change the value of "test" in "script" object to &lt;code&gt;mocha&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;run &lt;code&gt;npm test&lt;/code&gt; to start the test&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;describe&lt;/code&gt; and &lt;code&gt;it&lt;/code&gt; funcitons accept two parameters, one is the descriptive message, the second one is the call back funciton.&lt;/li&gt;
&lt;li&gt;The callback function should has &lt;em&gt;setup&lt;/em&gt;, &lt;em&gt;execise&lt;/em&gt;, &lt;em&gt;verify&lt;/em&gt; and &lt;em&gt;teardown&lt;/em&gt; sections.

&lt;ul&gt;
&lt;li&gt;variables are declared in setup section&lt;/li&gt;
&lt;li&gt;execute functions in execise section&lt;/li&gt;
&lt;li&gt;and verify the result with the expectedValue &lt;/li&gt;
&lt;li&gt;teardown makes the tests isolated so it's not affected or affecting other tests.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Hooks can make setup and teardown easier. (&lt;strong&gt;Note&lt;/strong&gt;: The example below works for mocha, it may vary in other test package)

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;beforeEach(callback)&lt;/code&gt; callback is run before each test&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;afterEach(callback)&lt;/code&gt; callback is run after each test&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;before(callback)&lt;/code&gt; callback is run before the first test&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;after(callback)&lt;/code&gt; callback is run after the last test&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;TDD stand for test driven development, it is guided by red-green-refactor cycle. The test is first written, then write the minimum amound of implement code to pass the test and then refactor the code.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;code coverage&lt;/em&gt; can depend on:

&lt;ul&gt;
&lt;li&gt;function coverage: all the funcitons are called&lt;/li&gt;
&lt;li&gt;statement coverage: all the statements are run?&lt;/li&gt;
&lt;li&gt;path coverage: every edge?&lt;/li&gt;
&lt;li&gt;condition coverage: both the boolean value tested?&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://www.codecademy.com"&gt;reference from codecademy&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>JavaScript: Node.js (built in modules)</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Fri, 14 Oct 2022 23:05:39 +0000</pubDate>
      <link>https://forem.com/rosiequ/javascript-nodejs-ool</link>
      <guid>https://forem.com/rosiequ/javascript-nodejs-ool</guid>
      <description>&lt;ol&gt;
&lt;li&gt;An error must be thrown to halt the program. &lt;code&gt;console.log(new Error('this is an error'))&lt;/code&gt; doesn't stop program from running.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;console.table()&lt;/code&gt; print out the elements in an object as a table&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;console.assert()&lt;/code&gt; print out false if the statement in the parenthesis is falsy.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;process is a global module. (Buffer, Error are also global module)&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;process.argv[0] returns the path of node;
process.argv[1] returns the file name;
process.argv[2] returns the first word in user input;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;5.node uses error-first call back function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const callbackFunc = (err, data)=&amp;gt;{err? console.log(err): console.log(data)}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;6.&lt;code&gt;fs&lt;/code&gt; is the built in module to interact with file system&lt;br&gt;
&lt;a href="https://www.makeuseof.com/node-write-files-learn/"&gt;Difference between fs.writeFile() and fs.createWriteStream()&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;fs.writeFile()&lt;/code&gt; requires all the content of the file at once;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;fs.createWriteStream()&lt;/code&gt; supports sequential writing.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const writeableStream = fs.createWriteStream('text.txt')
process.stdin.pipe(writableStream);
//output: all the input from terminal when the terminal is open.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;fs.createWriteStream()&lt;/code&gt; can also work with &lt;code&gt;fs.createReadStream()&lt;/code&gt; to copy file from one to another
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let readableStream = fs.createReadStream("test.txt");
let writableStream = fs.createWriteStream("test2.txt");

readableStream.on("data", function(chunk) {
    writableStream.write(chunk);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;7.event module provides an &lt;code&gt;EventEmitter&lt;/code&gt; class. Example of creating an instance of EventEmitter class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const events = require('events');
const myEmitter = new events.EventEmitter();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Each instance has a &lt;code&gt;.on()&lt;/code&gt; method which assigns a callback function to a named event. The first argument is the name of the event as a string, the second argument is the callback.&lt;/li&gt;
&lt;li&gt;Each instance also has a &lt;code&gt;.emit()&lt;/code&gt; method which announces the named event has occured. The first argument is the name of the event, the second argument is the data that should be passed into the callback function.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;8.&lt;code&gt;console.log()&lt;/code&gt; is a thin wrapper of &lt;code&gt;process.stdout.write()&lt;/code&gt;, to receive input from a terminal, use &lt;code&gt;process.stdin.on()&lt;/code&gt;&lt;br&gt;
9.&lt;code&gt;Buffer&lt;/code&gt; module has several methods to handle binary data.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.alloc()&lt;/code&gt; creates a new Buffer object. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.toString()&lt;/code&gt; transfer the Buffer object to a string.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.from()&lt;/code&gt; can create an Buffer from a string&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.concat()&lt;/code&gt; joins all the buffer objects in an array into one buffer object.(this method comes in handy because a Buffer object can't be resized.)
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const buffer = Buffer.alloc(5,'b');
console.log(buffer); //output: &amp;lt;Buffer 62 62 62 62 62&amp;gt;
console.log(buffer.toString()) //output: bbbbb
const buffer1 = Buffer.from('hello')
const buffer2 = Buffer.from('world')
console.log(buffer1) //output: &amp;lt;Buffer 68 65 6c 6c 6f&amp;gt;
const bufferConcat = Buffer.concat([buffer1, buffer2])
console.log(bufferConcat) //output: &amp;lt;Buffer 68 65 6c 6c 6f 77 6f 72 6c 64&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;10.&lt;code&gt;setImmediate()&lt;/code&gt; execute the callback function inside after the &lt;strong&gt;current&lt;/strong&gt; poll is completed.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>JavaScipt: Express.js</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Fri, 14 Oct 2022 22:05:56 +0000</pubDate>
      <link>https://forem.com/rosiequ/javascipt-expressjs-dj0</link>
      <guid>https://forem.com/rosiequ/javascipt-expressjs-dj0</guid>
      <description>&lt;ul&gt;
&lt;li&gt;Node.js is a runtime environment that allows Javascript files to run outside of browser runtime; &lt;code&gt;Express.js&lt;/code&gt; is a server-side framework built to work with Node.js&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CRUD&lt;/code&gt; means the api allows clients to create, read, update and delete information.&lt;/li&gt;
&lt;li&gt;Require the express module and invoke an instance.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express')
const app = express()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;app.listen(PORT, callback)&lt;/code&gt; can start a server. The first parameter is the port number argument tells the server where to listen; the callback function is executed when the server is listening and ready for response.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;route&lt;/code&gt; is a section of Express code that is associated with an HTTP verb, a url path, and a function that is called to handle that pattern.&lt;/li&gt;
&lt;li&gt;Express searches through the routes and responses with the first route matches the request url.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;path&lt;/code&gt; is part of the requested url after the hostname and port.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  HTTP verb(GET,PUT,UPDATE,DElETE)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;app.get()&lt;/code&gt; is used to match the route with GET request. The first parameter is the route path(string), the second parameter is the callback function to handle the request and send a response. When a requested url arrives, &lt;code&gt;req.params&lt;/code&gt; object will store the information from the requested url path. (query string is not necessary)
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/monsters/:name', (req, res, next) =&amp;gt; {
  res.send(...); // or res.json() to send json format response
});
//request url : 'monsters/rx'  req.params = {name: 'rx'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;app.put()&lt;/code&gt; is used to update existing data from the database. It needs data from &lt;code&gt;query string&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;app.post()&lt;/code&gt; is used to create a new resources. It needs data from &lt;code&gt;query string&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;app.delete()&lt;/code&gt; is used to delete a resource. (query string is not necessary)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  req.params and req.query
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;route parameter&lt;/code&gt; is in route path and begins with &lt;code&gt;':'&lt;/code&gt; it. &lt;code&gt;req.params&lt;/code&gt; stores route parameters in an object. It is like a &lt;strong&gt;unique identifier&lt;/strong&gt; for the database, so the server can send the requested resource.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;query string&lt;/code&gt; is the part of url after &lt;code&gt;'?'&lt;/code&gt;. Express parse the information into &lt;code&gt;req.query&lt;/code&gt; object. The value of the key is a &lt;strong&gt;string&lt;/strong&gt;. It stores information the client send to the server.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Router
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;using router can make code cleaner. It adds the router path to the path in &lt;code&gt;app.use()&lt;/code&gt;
Eg:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in router.js file:
const monserRouter = express.Router()
monsterRouter.get('/:name',(req,res,next)=&amp;gt;{....})
module.exports = monsterRouter;

// in main.js file
const monsterRouter = require('./router.js')
app.use('/monster',monsterRouter)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  res.status
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhrsiysiukv6bb3uz0vs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhrsiysiukv6bb3uz0vs.png" alt="status code" width="798" height="432"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>JavaScript: Module export and import (browser and Node.js runtime)</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Thu, 06 Oct 2022 23:31:56 +0000</pubDate>
      <link>https://forem.com/rosiequ/javascript-module-119n</link>
      <guid>https://forem.com/rosiequ/javascript-module-119n</guid>
      <description>&lt;p&gt;====================================&lt;/p&gt;

&lt;h2&gt;
  
  
  Browser runtime
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open a HTML file with js modules directly from default browser will throw an error. You need to create a &lt;strong&gt;local server&lt;/strong&gt; with VSCode.&lt;/li&gt;
&lt;li&gt;The script.js file has imported module should have an attribute &lt;code&gt;type= 'module'&lt;/code&gt; when linking to HTML, the file has exported module doesn't need to be linked to HTML.&lt;/li&gt;
&lt;li&gt;To export several functions, &lt;code&gt;export {func1, func2...}&lt;/code&gt; or add &lt;code&gt;export&lt;/code&gt; before declare the function&lt;/li&gt;
&lt;li&gt;To import a function &lt;code&gt;func&lt;/code&gt; and rename it to &lt;code&gt;newfunc&lt;/code&gt;, &lt;code&gt;import {func as newfunc} from 'path'&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;To export a function as default, use &lt;code&gt;export {func as default}&lt;/code&gt; or simply &lt;code&gt;export default func&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;To import a default value, &lt;code&gt;import importfunc from path&lt;/code&gt; works the same with &lt;code&gt;import { default as importedResources } from 'path'&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;object-destructuring in import.
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"&gt;MDN Web Docs on object destructuring&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const resources = {
  func1,
  func2
}
export default resources;

import resources from 'path'
const {func1, func2} = resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;====================================&lt;/p&gt;

&lt;h2&gt;
  
  
  Node.js runtime
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;module.exports.func1 = func1&lt;/code&gt; to export function1. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;const func1 = require('./path')&lt;/code&gt; to import values. For built in module, no need to provide the path.&lt;/li&gt;
&lt;li&gt;object-destructuring in import:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
  func1,
  func2
}

import way 1:
const func = require('path');
const func1Value = func.func1;
const func2Value = func.func2;

import way 2:
const {func1, func2} = require('path')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>JavaScript: OOP-Class</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Sat, 17 Sep 2022 05:32:43 +0000</pubDate>
      <link>https://forem.com/rosiequ/javascript-class-aof</link>
      <guid>https://forem.com/rosiequ/javascript-class-aof</guid>
      <description>&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Classes are templates for objects&lt;/strong&gt;. The name of a class should have the first letter capital and the rest in camalcase.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;An instance is an object that contains the property name and method of a class&lt;/strong&gt;. &lt;/li&gt;
&lt;li&gt;When we create a new instance with the keyword &lt;code&gt;new&lt;/code&gt;, the constructor method is called.
Note: class methods and getter syntax are the same with objects. &lt;strong&gt;BUT&lt;/strong&gt; no commas between methods.&lt;/li&gt;
&lt;li&gt;To call a method: &lt;code&gt;instance.methodname()&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Inheritance allows the child class to use share property and method. The &lt;code&gt;extend&lt;/code&gt; keyword makes the method and getters of parent class available in the child class. The &lt;code&gt;super&lt;/code&gt; keyword calls the constructor method in the parent class.&lt;/li&gt;
&lt;li&gt;Static method can only be called directly from the class. It can't be used on an instance of a class or subclass. (don't forget the &lt;code&gt;()&lt;/code&gt; at the end)
example code:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Animal {
    constructor(breed, gender) {
        this._breed = breed;
        this._gender = gender;
        this._vaccine = 0;
    }
    get breed() {
        return this._breed;
    }
    get gender() {
        return this._gender;
    }
    get vaccine() {
        return this._vaccine;
    }
    vaccineShot(num) {
        this._vaccine += num;
    }
    static generateName(){
        const nameArr=['Milo','Cookie','Sandy','Odin'];
        return nameArr[Math.floor(Math.random()*3)]
    }
}
class Dog extends Animal {
    constructor(breed, gender, age) {
        super(breed, gender);
        this._age = age;
    }
    get age(){
        return this._age;
    }
    increaseAge(num){
        this._age+=num;
    }
}
const dahuang = new Dog('Golden Retriever', 'Male',1);
dahuang.vaccineShot(2)
console.log(dahuang)
//Output: DogHome { _breed: 'Golden Retriever', _gender: 'Male', _vaccine: 2, _age: 1 }
console.log(dahuang.vaccine)
//Output: 2
dahuang.increaseAge(1);
console.log(dahuang.age)
//Output: 2
console.log(Animal.generateName());
//Output: Milo

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

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>JavaScript: Async and Request</title>
      <dc:creator>Ruxin Qu</dc:creator>
      <pubDate>Thu, 15 Sep 2022 23:46:42 +0000</pubDate>
      <link>https://forem.com/rosiequ/javascript-async-and-request-4lke</link>
      <guid>https://forem.com/rosiequ/javascript-async-and-request-4lke</guid>
      <description>&lt;ol&gt;
&lt;li&gt;JavaScript is a single-thread language. But the event loop allows it to run asynchronous code.&lt;/li&gt;
&lt;li&gt;The event loop has four parts: memory heap, call stack, event queue and event loop.

&lt;ul&gt;
&lt;li&gt;The heap stores the variable and object currently in use. &lt;/li&gt;
&lt;li&gt;The call stack tracks the function that's currently running. When a function is invoked, a frame is added to the call stack in a LIFO(last in first out) order. &lt;/li&gt;
&lt;li&gt;The messages returned from API will be sent to wait in the queue.&lt;/li&gt;
&lt;li&gt;And the event loop always brings the first message to the stack if the stack is empty.
&lt;strong&gt;Note&lt;/strong&gt;: setTimeout() is a Node function which delays the execution of a callback function using the event-loop.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Promises are objects that represent the eventual outcome of an asynchronous operation. A promise can have three states: pending, fulfilled, rejected.A promise is settled if it is either resolved or rejected.

&lt;ul&gt;
&lt;li&gt;Example of a promise is handled by two callback functions
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleSuccess = (res) =&amp;gt; {
    console.log(res);
}
const handleFailure = (rej) =&amp;gt; {
    console.log(rej);
}
const checkNum = (num) =&amp;gt; {
    return new Promise((resolve, reject) =&amp;gt; {
        if (num &amp;gt; 2) {
            resolve('this num is larger than 2');
        }
        else {
            reject('this num is less than 2');
        };
    })
};
checkNum(5).then(handleSuccess).catch(handleFailure);
// output: this num is larger than 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.then(handleSuccess,handleFailure)&lt;/code&gt; is equal to &lt;code&gt;.then(handleSuccess).catch(handleFailure)&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4.When three functions are independent, use &lt;code&gt;Promise.all([fun1, fun2, fun3])&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;


&lt;ol&gt;
&lt;li&gt;The &lt;code&gt;async&lt;/code&gt; keyword is used to write functions with asynchronous actions. Async functions will always return a promise.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const exampleFunction = async ()=&amp;gt;{
    return 5
}
exampleFunction()
.then((res)=&amp;gt;{
    console.log(res)
})
.catch((rej)=&amp;gt;{
    console.log(rej)
})
//Output: 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;2.&lt;code&gt;await&lt;/code&gt; halts the execution of a function until a given promise is resolved. If a promise is still pending, the log result will be pending promise.&lt;br&gt;
3.try{}catch(err){console.log(err)} can be used to handle error.&lt;br&gt;
4.When multiple functions can happen simultaneously, use &lt;code&gt;await Promise.all()&lt;/code&gt;. The resolved value is an array with all the resolved promise from the argument array. The soon as one promise is rejected, it rejects and returns the reject reason from that promise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function asyncPromAll() {
  const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]);
  for (let i = 0; i&amp;lt;resultArray.length; i++){
    console.log(resultArray[i]); 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ol&gt;
&lt;li&gt;fetch url is made by &lt;code&gt;${baseUrl}${endPoint}${requestParams}&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;GET request
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('http://api-to-call.com/endpoint')
.then(response =&amp;gt; {
  if (response.ok) {
    return response. json();
  }
  throw new Error('Request failed!');
}, networkError =&amp;gt; console.log(networkError.message)
). then (isonResponse =&amp;gt; {
// Code to execute with isonResponse
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getData = async () =&amp;gt; {
    try {
        const response = await fetch('https://api-to-call.com/endpoint');
        if (response.ok) {
            const jsonResponse = await response.json();
            //code to do with response
        }
        throw new Error('Request failed!');
    } catch (error) {
        console.log(error);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3.POST request&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('http: //api-to-call.com/endpoint', {
    method: 'POST',
    body: JSON.stringify({ id: '200' })
}).then(response =&amp;gt; {
    if (response.ok) {
        return response.ison();
    }
    throw new Error('Request failed!');
}, networkError =&amp;gt; console.log(networkError.message)
).then(jsonResponse =&amp;gt; {
    // Code to execute with isonResponse
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getData = async () =&amp;gt; {
    try {
        const response = await fetch('https://api-to-call.com/endpoint', {
            method: 'POST',
            body: JSON.stringify({ id: 200 })
        });
        if (response.ok) {
            const jsonResponse = await response.json();
            //code to do with response
        }
        throw new Error('Request failed!');
    } catch (error) {
        console.log(error);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://www.codecademy.com/learn"&gt;Resource referenced: Codecademy.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
