developing a deferred commitment by utilizing promise objects

Hi everyone, I've encountered an issue with a JavaScript promise question that's throwing errors

function delay(n) {
    return new Promise((resolve) => setTimeout(resolve, n*1000));
}

The expected output should be "It is now 2 seconds later" and then "It is now 1.5 seconds later" but instead, it displays:

It is now undefined later
It is now undefined later

delay(2)
    .then(seconds => console.log(`It is now ${seconds} later`))
    .then(()=> delay(1.5))
    .then(seconds => console.log(`It is now ${seconds} later`));

Answer №1

Ensure to include a resolve value by updating setTimeout(resolve with

setTimeout(function() {resolve(n);}
.

Answer №2

setTimeout has the ability to accept multiple parameters;

setTimeout(function, milliseconds, param1, param2, ...)

After setting the timeout duration in milliseconds as the second parameter for setTimeout, you can provide additional parameters as needed;

For instance:

setTimeout(resolve, n*1000)

You can modify it to:

setTimeout(resolve, n*1000, n)

function delay(n) {
    return new Promise((resolve) => setTimeout(resolve, n*1000, n));
}
delay(2)
    .then(seconds => console.log(`It is now ${seconds} seconds later`))
    .then(() => delay(5))
    .then(seconds => console.log(`It is now ${seconds} seconds later`));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to perform filtering on a nested array object within a computed property using Vue while displaying data in a table

Lately, I've been experimenting with different methods to filter data in my project. I've tried using various approaches like methods and watchers, but haven't quite achieved the desired outcome yet. Essentially, what I'm aiming for is ...

Exploring the functionality of Kendo Grid within an Angular application

Currently, I am facing some challenges while trying to execute my Karma tests using the kendo grid within a fresh Angular project. The specifications for this specific component are outlined below: import { async, ComponentFixture, TestBed } from '@a ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...

When using the `coffee-util` library, an issue may arise if the `require('./module')` function ends

When I develop using CoffeeScript 1.6.3, I simply run my application with coffee myapp. I also use coffee -c . to check the resulting .js files. However, when I try running coffee myapp again, the coffee utility for require(./module) uses .js files inste ...

Guide on toggling the expansion and collapse of antd TreeSelect items when a button is clicked

I recently started using the antd library to develop my website. I have successfully implemented the TreeSelect component to display nested options. However, I am currently facing an issue: I am attempting to expand and collapse TreeSelect items when a b ...

Showing JSON data in AngularJS

I need help with AngularJS to display JSON output. Is using gridOptions the best approach for this? I'm trying to print labels starting from the root in reverse order - label/parent's label/parent's parent's label/... { artifac ...

Is there a method in Vuejs to choose a tab and update components simultaneously?

Currently facing an issue where selecting a tab does not refresh the input field in another component, causing data persistence. The data is stored in vuex, so I'm looking for a solution to refresh the component for usability. Appreciate any assistanc ...

Add custom CSS styles to a webpage using the CSS Style element retrieved from

I am working on an HTML page that has a TextArea and label. My goal is to create CSS classes in the TextArea and apply them to the label: <textarea id="txtCSS" name="txtCSS" rows="4" cols="50"> .FC{color:gr ...

Unexpected token . encountered in Javascript: Uncaught Syntax Error. This error message is triggered when

As someone who is completely new to programming, I was given the task of creating a voting website for a class assignment. In order to store data locally, I managed to create variables and implement them using local storage: var eventName = document.getEl ...

What is the process of refreshing a page post-loading?

I'm working on a fundraising webpage and I want to display the live amount of money raised. Essentially, when one user donates while another is viewing the total amount raised, I want the displayed number to update in real-time. My backend setup incl ...

A guide on how to insert content into a text area using a drop-down menu choice

I'm a total beginner at this. Is it possible to use JavaScript to automatically fill in a text area on an HTML form based on what is selected in a drop-down menu? If so, can someone please explain how to achieve this? ...

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

Exploring ways to retrieve item metadata from a Stripe checkout session

When setting up a Checkout session, I dynamically create prices using the price_data and product_data properties. I include metadata for each item within the product_data.metadata property. However, after a successful payment is made, I retrieve the sessi ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

What steps can I take to resolve this issue when encountering an error during npm install?

As a newcomer to programming, I am embarking on the creation of a Discord bot using node and discord.js. My current hurdle involves the installation of a library named canvas, which seems to be causing issues. After developing and testing my application o ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

I'm facing issues with Angular commands not functioning properly even after installing the Angular CLI and configuring the

Every time I attempt to create a new project using Angular CLI by typing: ng n app I encounter the following error message: C:\Users\Venkateshwarn M\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng: ...