Own Promises, Accessing Arguments, Async/Await

 

1. Asynchronous JS code style

There are two main types of asynchronous code style you'll come across in JavaScript:

  • Callback based Example :

    setTimeout()
    ,
    setInterval()

  • Promise based Example :

    fetch()

2. Creating your own Promises

Promises are the new style of async code that you'll see used in modern JavaScript.

Syntax :

const myPromise = new Promise((resolveFunction, rejectFunction) => {
//Async task
});

In the above syntax:

  • The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve, which must be called when the Promise is resolved (passing a result), and reject when it is rejected (passing an error).
  • The executor is to be executed by the constructor, during the process of constructing the new Promise object.
  • resolveFunction is called on promise fulfilled.
  • rejectFunction is called on promise rejection.

Example :

const myPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 1000);
});
};
console.log(myPromise());
JAVASCRIPT

2.1 Accessing Arguments from Resolve

When

resolve()
is excuted, callback inside
then()
will be executed.

Example :

const myPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise Resolved");
}, 1000);
});
};
myPromise().then((fromResolve) => {
console.log(fromResolve); // Promise Resolved
});
JAVASCRIPT
Collapse

2.2 Accessing Arguments from Reject

When

reject()
is excuted, callback inside
catch()
will be executed.

Example :

const myPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject("Promise Rejected");
}, 2000);
});
};
myPromise()
.then((fromResolve) => {
console.log(fromResolve);
})
.catch((fromReject) => {
console.log(fromReject); // Promise Rejected
});
JAVASCRIPT
Collapse

3. Async/Await

  1. The Async/Await is a modern way to consume promises.
  2. The Await ensures processing completes before the next statement executes.

Syntax :

const myPromise = async () => {
let promiseObj1 = fetch(url1);
let response1 = await promiseObj1;
let promiseObj2 = fetch(url2);
let response2 = await promiseObj2;
};
myPromise();
Note
  1. Use async keyword before the function only if it is performing async operations.
  2. Should use await inside an async function only.

3.1 Fetch with Async and Await

Example :

const url = "https://apis.ccbp.in/jokes/random";
const doNetworkCall = async () => {
const response = await fetch(url);
const jsonData = await response.json();
console.log(jsonData);
};
doNetworkCall();
JAVASCRIPT

3.2 Error Handling with Async and Await

Example :

const url = "https://a.ccbp.in/jokes/random";
const doNetworkCall = async () => {
try {
const response = await fetch(url);
const jsonData = await response.json();
console.log(jsonData);
} catch (error) {
console.log(error);
}
};
doNetworkCall();
JAVASCRIPT
Collapse

3.3 Async Function always returns Promise

Example :

const url = "https://apis.ccbp.in/jokes/random";
const doNetworkCall = async () => {
const response = await fetch(url);
const jsonData = await response.json();
console.log(jsonData);
};
const asyncPromise = doNetworkCall();
console.log(asyncPromise);
JAVASCRIPT

4. String Manipulations

There are methods and properties available to all strings in JavaScript.

String MethodsFunctionality
toUpperCase(), toLowerCase()Converts from one case to another
includes(), startsWith(), endsWith()Checks a part of the string
split()Splits a string
toString()Converts number to a string
trim(), replace()Updates a string
concat(), slice(), substring()Combines & slices strings
indexOf()Finds an index

4.1 trim()

The

trim( )
method removes whitespace from both ends of a string.

Syntax :

string.trim()

const greeting = " Hello world! ";
console.log(greeting);
console.log(greeting.trim());
JAVASCRIPT

4.2 slice()

The

slice()
method extracts a section of a string and returns it as a new string, without modifying the original string.

Syntax :

string.slice(start, end)

const text = "The quick brown fox";
console.log(text.slice(0, 3)); // The
console.log(text.slice(2, 3)); // e
JAVASCRIPT

4.3 toUpperCase()

The

toUpperCase()
method converts a string to upper case letters.

Syntax :

string.toUpperCase()

const text = "The quick brown fox";
console.log(text.toUpperCase()); // THE QUICK BROWN FOX
JAVASCRIPT

4.4 toLowerCase()

The

toLowerCase()
method converts a string to lower case letters.

Syntax :

string.toLowerCase()

const text = "Learn JavaScript";
console.log(text.toLowerCase()); // learn javascript
JAVASCRIPT

4.5 split()

The

split()
method is used to split a string into an array of substrings and returns the new array.

Syntax :

string.split(separator, limit)

const str = "He-is-a-good-boy";
const words = str.split("-");
console.log(words); // ["He", "is", "a", "good", "boy"]
JAVASCRIPT

4.6 replace()

The

replace()
method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

Syntax :

string.replace(specifiedvalue, newvalue)

const str = "Welcome to Hyderabad";
const words = str.replace("Hyderabad", "Guntur");
console.log(words); // Welcome to Guntur
JAVASCRIPT

4.7 includes()

  1. The

    includes()
    method determines whether a string contains the characters of a specified string.

  2. It returns

    true
    if the string contains the value, otherwise it returns
    false
    .

Syntax :

string.includes(searchvalue, start)

const str = "Learn 4.0 Technologies";
const word = str.includes("Tech");
const number = str.includes("5.0");
console.log(word); // true
console.log(number); // false
JAVASCRIPT

4.8 concat()

The

concat()
method is used to join two or more strings.

Syntax :

string.concat(string1, string2, ..., stringX)

const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(str2)); // HelloWorld
console.log(str1.concat(" Pavan", ". Have a nice day.")); // Hello Pavan. Have a nice day.
JAVASCRIPT

4.9 indexOf()

The

indexOf()
method returns the position of the first occurrence of a specified value in a string.

Syntax :

string.indexOf(searchvalue, start)

const str = "Building Global Startups";
console.log(str.indexOf("Global")); // 9
console.log(str.indexOf("up")); // 21
JAVASCRIPT

4.10 startsWith()

The

startsWith()
method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

Syntax :

string.startsWith(searchvalue, start)

const str = "World-class Products";
console.log(str.startsWith("rld")); // false
console.log(str.startsWith("World")); // true
JAVASCRIPT

4.11 endsWith()

The

endsWith()
method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

Syntax :

string.endsWith(searchvalue, length)

const str = "How are you?";
console.log(str.endsWith("you?")); // true
console.log(str.endsWith("re")); // false
JAVASCRIPT

4.12 toString()

The

toString()
method returns the value of a string object.

Syntax :

string.toString()

const number = 46;
const newNumber = number.toString();
console.log(newNumber); // 46
console.log(typeof newNumber); // string
JAVASCRIPT

4.13 substring()

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

Syntax :

string.substring(start, end)

const str = "I am learning JavaScript";
console.log(str.substring(2, 9)); // am lear
console.log(str.substring(6)); // earning JavaScript
JAVASCRIPT

4.14 Length

The

length
property returns the length of a string (number of characters).

Syntax :

string.length

const str = "Upgrade to CCBP Tech 4.0 Intensive";
console.log(str.length); // 34
JAVASCRIPT

Try out different string manipulations in the JavaScript Code Playground.

Practice Async Await with Promises

Search Item in a Mart Given an array mart of objects in the prefilled code and categoryOfItem , item as inputs, create a JS promise, resolve with "Item Found" text, if the categoryOfItem matches with the category and the corresponding items list includes the item reject with "Category Not Found" text, if the categoryOfItem does not match with any category in the mart reject with "Item Not Found" text, if the items list does not include item Use async/await and try/catch blocks with the help of find() and includes()


How to use multiple Promise with try catch Block.

Gardening 

We have a task to do Gardening. 
Given two boolean values isGrassTrimmerFound and isWaterHosePipeFound as inputs, 
create three JS promises using async/await and try/catch blocks. 

 For cutting the grass, resolve with "Grass Trimmed" text, if the isGrassTrimmerFound is true reject with "Grass Trimmer Not Found" text, 
if the isGrassTrimmerFound is false For cleaning the garden, resolve with "Garden Cleaned" text For watering the plants, resolve with "Watered Plants" text, 
if the isWaterHosePipeFound is true reject with "Water Hose Pipe Not Found" text, if the isWaterHosePipeFound is false.

....

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form