Hoppscotch Pre-request Script async request

  Kiến thức lập trình

I’m experiencing an issue with the asynchronous execution order of .then() in a fetch request within my JavaScript script. The script is supposed to fetch an authentication token and then set it in an environment variable. However, it seems like the URL call for my application is happening before the .then() chains execute, leading to the use of an unset token. I need the token to be retrieved and set before making a subsequent request. So it successfully retrieves the token and the script is being executed until the first part of fetch, but before the .then it calls the url and then executes the rest of the script.

const authUrl = "https://auth0.com/oauth/token";
const authBody = JSON.stringify({
  grant_type: "password",
  client_id: "client_id",
  client_secret: "client_secret",
  scope: "openid profile email",
  audience: "https://audience/",
  username: "username",
  password: "password"
});
console.log("nach dem ziehen des token")
// Execute the fetch request to authenticate
fetch(authUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: authBody
})
.then(response => response.json())
.then(data => {
  if (data.access_token) {
    // Set the access token in an environment variable
    pw.env.set("accessToken", data.access_token);
        pw.env.set("accessToken", data.access_token);
    console.log("accessToken set:", data.access_token); // to check the log
  } else {
    console.error('Error retrieving the token:', data);
  }
})
.catch(error => console.error('Error in fetching auth token:', error));

LEAVE A COMMENT