"Assure that setTimeout will be executed within the then method in

Within an Immediately Invoked Function Expression (IFFE), I am returning a Promise. The first thing that is logged is first, followed by third, and then second. Despite having the setTimeout inside the then block, shouldn't everything within it be executed synchronously?

(() => {
    return new Promise(resolve => {
       console.log("first")
       resolve()
    })
    .then(() => {
       setTimeout(() => console.log("second"), 3000)
    })


})()
.then(() => console.log("third"))

Answer №1

To implement the use of setTimeout within a Promise, you need to create an additional promise and resolve it inside the setTimeout function. This is demonstrated in the code snippet below:

new Promise(resolve => setTimeout(resolve, 3000));

Here's how it looks in a larger context:

new Promise(resolve => {
  console.log('first');
  resolve();
})
  .then(
    () =>
      new Promise(resolve =>
        setTimeout(() => {
          console.log('second');
          resolve();
        }, 3000)
      )
  )
  .then(() => console.log('third'));

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

How to sort WordPress RSS feed in alphabetical order using JavaScript

Currently using WP, but feeling limited due to restricted access to PHP and plugins. Searching for a JAVASCRIPT code solution to fetch RSS feed from a URL and organize the feed titles in ALPHABETICAL order. The JS code can be inserted into the footer and ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

What is the best way to delete a container when its child element includes a specific string?

I run a website that compiles video clips from various sources, including YouTube. Occasionally, some clips appear as private videos. I am looking to use jQuery to apply the display:none; property to the entire div when the class a.colorbox.cboxElement con ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

Trapped in the Web of Facebook OAuth

I've been struggling with this issue for a day now and I can't seem to pinpoint where I'm going wrong. I have experience working with JavaScript on the client side and recently started following a book tutorial. However, it appears that Face ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

Ways to combine X and Y velocities into a single velocity

Is there a way to combine the X and Y Velocity into a single Velocity without considering the angle? var velocityX = some value; var velocityY = some value; // Need to convert both X and Y velocities into one combined velocity ...

Tips for injecting an Angular variable into a JavaScript variable

Within my angular controller, I have a function defined as follows: $scope.get_all_places = function () { $http.get("get-all-places").then(function (response) { $scope.selected_place = eval(response.data[0]); }); }; I am trying to assign ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Ways to ensure that a URL is distinct once a link has been clicked

On my website list.php, I have a code snippet that changes the video in an iframe when a link is clicked. However, the URL remains as list.php instead of changing to something like list.php/Anohana10. How can I update the URL to reflect the selected video? ...

How to Stop Form from Automatically Submitting in Laravel 5.5 and vue-typeahead's onHit method

I have integrated the vue-typeahead component into my Laravel project using vue-typeahead. However, I am facing an issue where when I select an entry from the result list by pressing the "enter" key, the form automatically submits. Is there a way to preve ...

Is it possible for a JavaScript .execute function to be executed synchronously, or can it be transformed into an Ajax

Currently, I am utilizing the ArcGIS API for Javascript which can be found at this URL: The JavaScript code snippet I'm working with appears to be running asynchronously. Is there a way to convert it to run synchronously or potentially transform it i ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

The markers on Google Maps are currently displaying in the wrong position, despite the latitude and longitude being correct

Utilizing the Google Maps API, I have implemented a system to dynamically add map markers tracking 2 of our company's vehicles. The website is developed in asp.net c# mvc with bootstrap 4.3.1. An ajax request retrieves the latest marker location from ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

How can I reposition an image diagonally to a specific location using JavaScript in p5.js? Is there a method to display an image and then conceal it at a chosen location in p5.js?

Is there a way to move the third image diagonally until it intersects with the two images? var pic1; var pic2; var pic3; let posX=0 let posY=0 const rightwall=350; function preload(){ pic1=loadImage("5.png") pic2=loadImage("iron.jpg&qu ...

Assign an attendee the role of organizer in the Google Calendar API

I am currently utilizing the googleapis npm package to facilitate calendar event creation. Below is my request payload for calendar.events.insert in order to generate an event: { "summary":"Biology class", "location":"Google Meet: Please follow the go ...

Scrolling to a specific position on a page when a Vue 3 component appears is a must-do for

When I click a button, my basic form component appears without using the router. I would like the scroll position of the form to automatically move down slightly (for example, on the y-axis at 40) once it is displayed. However, I am unsure of how to achi ...

Creating a hover effect for displaying image masks

My website features a profile page displaying the user's photo. I am attempting to create a functionality where when the user hovers over their photo, a transparent mask with text appears allowing them to update their profile picture via a modal. How ...