
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Resolving or rejecting promises accordingly - JavaScript
We are required to write a JavaScript function that imitates a network request, for that we can use the JavaScript setTimeout() function, that executes a task after a given time interval.
Our function should return a promise that resolves when the request takes place successfully, otherwise it rejects
Example
Following is the code −
const num1 = 45, num2 = 48; const res = 93; const expectedSumToBe = (num1, num2, res) => { return new Promise((resolve, reject) => { setTimeout(() => { if(num1 + num2 === res){ resolve('success'); }else{ reject('failure'); }; }, 3000); }); }; expectedSumToBe(num1, num2, res).then((data) => { console.log(data); }).catch((err) => { console.log(err); }) expectedSumToBe(23, 56, 76).then((data) => { console.log(data); }).catch((err) => { console.log(err); })
Output
Following is the output in the console −
success failure
- Related Articles
- JavaScript Promises
- What are Promises in JavaScript?
- Resolving Conflict Between States
- What are the differences between Deferreds, Promises and Futures in javascript?
- Resolving Power of Microscopes and Telescopes
- How to run a given array of promises in series in JavaScript?
- Promises Callbacks And Async/Await
- What are Promises in React.js?
- Promises of Marriage an Excuse of Rape
- How to use Typescript with native ES6 Promises?
- How to create FileFilter for JFileChooser in Java and display File Type accordingly?
- What is JavaScript Bitwise OR (|) Operator?
- HTML5 & JavaScript: resolution or size of
- Strictly increasing or decreasing array - JavaScript
- What is Logical OR Operator (||) in JavaScript?

Advertisements