Chai - Setting a variable inside a request

issueId is undefined when it should be returning an Id. How can I set a variable inside a request in Chai? Thanks

suite('Test Test(s)', () => {
  let issueId = "";

  test('PUT request', done => {
    .set('content-type', 'application/json')
      issue_title: "Issue Title",
      issue_text: "Issue Text",
      created_by: "Admin"
    .end((err, res) => {
      issueId = res.body._id;     

    console.log(issueId); // Returns undefined


You cannot use a declared variable outside of an asynchronous context. In this case, the .end(callback) is asynchronous, therefore the value will be set after you log it using console.log.

Take a look at this sample code:


<div class="outpu"></div>


.output {
  padding: 1rem;

.output span {
  display: block;
  width: 100%;
  padding: 1rem .5rem;

.output span:nth-child(odd) {
  background: #dedede;
  color: black;

.output span:nth-child(even) {
  background: #999;
  color: white;


const result = document.querySelector('.output');

function write(str) {
  const span = document.createElement('span');
  span.innerText = str;

write("Starting script");

function asyncFn(callback) {
	// Simulate a function that takes time to complete but returns immediately
  const t = setTimeout(() => {
  }, 1000);

write("Declaring contextual variable");
let contextVar;

function asyncFnCaller() {
  asyncFn((response) => {
  	write(`Result of the callback: ${response}`);
    contextVar = response;
    write(`contextVar inside the callback: ${contextVar}`);

write("Invoking the asyncFnCaller");

write(`Content of the context variable: ${contextVar}`)

In this code, the asyncFnCaller is like the .end function.

Try to understand how the example works and see if you can figure out why it doesn’t work :slight_smile:.

Something to increase your knowledge

1 Like

Thank you so much! Right now, I am very confused about Asynchronous Javascript. I’ll try to understand it as much as I can :smiley:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.