The Issue of Promises Chaining in Vue That is Causing Unexpected Behavior

Can’t seem to figure out what I’m missing here, so reaching out for help.

Simply put, I want to achieve this in Vue (https://codesandbox.io/s/6zlmkm61m3)

function p1() {
  return new Promise((resolve, reject) => {
    console.log('p1')
    resolve()
  })
}

function p2() {
  return new Promise((resolve, reject) => {
    console.log('p2')
    reject('p2')
  })
}

p1()
  .then(p2)
  .catch((error) => {
    console.log(error)
  })

When I try to do this in Vue, I encounter an Uncaught (in promise) error.

https://codesandbox.io/s/mq2343y6p8

I’m not certain if this issue is related to Vue or how I am invoking the methods. Any assistance would be greatly appreciated.

Vue code:

export default {
  name: "App",
  components: {
    Hello,
    World
  },
  data() {
    return {};
  },
  methods: {
    checkPromise() {
      this.$refs.promiseOne
        .p1()
        .then(this.$refs.promiseTwo.p2())
        .catch(error => {
          console.log(error);
        });
    }
  }
};

Answer №1

The issue lies within the following line:

.then(this.$refs.promiseTwo.p2())

Here, this.$refs.promiseTwo.p2 is meant to refer to the function that returns a Promise. However, instead of passing the function as a parameter to then as usual, you are calling the function and passing its result to .then.

To resolve this, modify the line to:

.then(this.$refs.promiseTwo.p2)

By making this change, the code should function correctly.

The snippet of code you provided on codesandbox, which has been translated into a live example here, is as follows:

function p1() {
  return new Promise((resolve, reject) => {
    console.log('p1')
    resolve()
  })
}

function p2() {
  return new Promise((resolve, reject) => {
    console.log('p2')
    reject('p2')
  })
}

p1()
  .then(p2()) // <------- issue: p2 is called, not passed
  .catch((error) => {
    console.log(error)
  })

(Please check the console of your actual browser on this page to see the error message Uncaught (in promise) p2)

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

Begin counting starting from 1 all the way up to 24, then feel free

I've developed a counter that increments from 0 to 24, and once it reaches 24: setInterval(function(){DayAndNight()}, 1000); var iState = 12; function DayAndNight() { //console.log('test'); switch(iState) ...

JavaScript change the object into a string

I've been working on code to convert strings into dictionaries and arrays, and vice versa. While string to array and string to object conversions are successful, the reverse process is giving me trouble. I'm currently stuck and unsure of how to r ...

Merge objects based on specific property within an array of objects

Is there a way to merge objects based on one property and also add missing Days names in the output? Consider this example: var array = [ { "heure1": "14:00", "heure2": "17:00", "day&q ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Creating a Draft.js selection with a specified start and end point

Looking for a way to replace the last insertion in Draft.js For instance, Original string -> aaazzz After inserting 'bbb' in the middle -> aaabbbzzz Replace last insert with 'ccc' -> aaaccczzz Replace last insert with &apos ...

Combining SSR and static content generation in NuxtJS 3: A Step-by-Step Guide

For a while now, I've been hearing about NuxtJS 3 and its upcoming Nitro engine that promises to handle both SSR and static generation. Despite my efforts, I haven't been able to locate any resources such as documents, tutorials, or videos detai ...

What is the best way to update the context while iterating through a jQuery each loop?

I am currently working on a code snippet that preprocesses response data retrieved from an AJAX call before displaying it (note: the display part is not included in this snippet). Specifically, it updates the src attribute of the image within each li eleme ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

Does the process of reading a `stream` consume resources in Node.js?

Node.js utilizes a stream as an abstract interface for handling streaming data. The node:stream module offers an API to implement this stream interface. During my exploration of NodeJs streams, I encountered confusion over whether a stream was involved in ...

Transferring data from PHP to JavaScript using AJAX

I'm currently working on a project that involves generating random numbers on both JavaScript and PHP pages, and I need to display them on the HTML page using JavaScript. So far, I have successfully set up both pages to generate random numbers. Howev ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

Moving files by dragging and dropping rather than deleting them

I have successfully implemented a feature using JavaScript to drag and drop multiple files, followed by displaying those images. The code below is fully functional without any errors. Need help with: I am now looking to add the ability to remove these ima ...

Utilizing multiple language files in Vue with vue-i18n: A comprehensive guide

Recently delving into vue and utilizing vuetify for my project, I managed to incorporate internationalization successfully. However, I am encountering difficulties with the standard method of a single file per language as my project expands, making maint ...

What is the best way to showcase a chart using jquery?

Is there a way to incorporate trendlines or target lines in highcharts similar to fusion chart? I have been able to draw them successfully in fusion charts. Check out this fiddle link: http://jsfiddle.net/Tu57h/139/ I attempted to recreate the same in hi ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

Is a postcss.config.js file necessary when setting up Tailwind CSS in Vue 3?

Having some trouble setting up Tailwind CSS 2.2.10 on a Vue 3 project without using Vite (so the instructions for "Install Tailwind CSS with Vue 3 and Vite" won't work). In the installation guide, the section on "Adding Tailwind as a PostCSS plugin" ...

Guide to handling multiple forms within a single template using Express

If I have an index.html file containing two tables - "Customers" and "Items", along with two forms labeled "Add customer" and "Add item", how can I ensure that submitting these forms results in a new entry being added to the respective table as well as t ...

Utilizing erb within a coffeescript file for modifying the background styling

Is there a way to change the background image of a div based on user selection from a dropdown menu? For instance, if the user picks "white" the background image becomes white, and for "red" it changes to red. I'm struggling with this in coffeescript ...

Communicating with my own account through Nodemailer

I have successfully set up nodemailer locally to handle email functionalities on my website. The goal is for it to extract the user's email input from an HTML form and then forward it to my Gmail account through a contact form. <form action="http: ...