question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Chaining multiple API calls results in async/sync mix error

See original GitHub issue

When chaining API calls in a cypress custom command, I am getting an error that says async/sync code is being mixed:

Desired behavior

This example only shows 2 API calls, but the end solution is going to require 3. I need to make 1 API call to return a token, another to get a user id, and then use both those returned values in a POST:

Steps to reproduce: (app code and test code)

I want to return the authID from the response, and then use it in then(authToken=>)

Cypress.Commands.add("ResetPwd", () => {
    return cy.request({
        method: 'POST',
        url: "https://example//token",
        headers: {
            'Content-Type': 'application/json',
        },
        body: {
            client_id: '1234',
            client_secret: '4321',
            audience: 'https://example.com/api/v2/',
            grant_type: 'credentials'
        }
    }).then(response => {
        const rbody = (response.body);
        var tokenPattern = "(?i)\"access_token\":\\s*\"([^\"]*)\"";
        const authToken = rbody.access_token;
        cy.log(authToken);
        return authToken
    }).then(authToken =>{
        cy.request({
            method: 'PATCH',
            url: "https://example.com/api/v2/users/33",
            headers: {
                'Content-Type': 'application/json',
                'authorization': 'Bearer '+authToken
            },
            body: {
                password: 'Test4321',
                connection: 'UserDB'
            },
        })
    })
});

When running this command, I get an error that says

CypressError: cy.then() failed because you are mixing up async and sync code.

In your callback function you invoked 1 or more cy commands but then returned a synchronous value.

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:1
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

13reactions
OACDesignscommented, Nov 11, 2019

I also encountered a similar issue recently as well. I had to remove the cy.log() call from the chain to resolve it.

Edit: I’ve replaced my cy.log with Cypress.log() instead. This is working well for me.

5reactions
valoricDecommented, Sep 9, 2020

Cypress is using a command queue, so regardless of what you are returning the last command result will be handed over to the next then call. Therefore if you want to return like a token and a userId you need to wrap your synchronous result in a cy.wrap({authToken, userId}). If you also want to make Typescript happy you need to change the return type of the then method to be as unknown as Chainable<{authToken: string, userId: number}>

Read more comments on GitHub >

github_iconTop Results From Across the Web

Chaining network requests with Combine Framework and ...
In this video, I demonstrate how to chain multiple network requests using combine framework and the new async await feature.
Read more >
“You are mixing async and sync code”- Fix in Cypress - Medium
Here, I will get the error, “ you are mixing up async and sync code. ... the callback function, its call yielded value...
Read more >
Angular/Ionic Chaining HTTP Calls Out of Sync - Stack Overflow
I'm currently working with an API that's a bit of a pain :D The API doesn't return full information needed for my app...
Read more >
Chaining tasks using continuation tasks | Microsoft Learn
Continuations allow descendant operations to consume the results of the ... Tasks; public class SimpleExample { public static async Task ...
Read more >
How to send multiple requests using axios - Storyblok
Let us start with a small task and sending one request using Axios itself. First, we import axios and define the API/URL we...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found