-7

I'm trying to learn JS Promises. I wrote the following piece of code just to see if it works, and the displayPersons() function runs before the 2 second timeout finishes.

The code basically has an array of objects called Persons. addPerson() adds another object to the Persons array. I want the persons to be displayed after the new person is added. But the output HTML is displayed immediately without the 2 second display and only shows the first person.

let persons = [
    {
        name:'Muhammad Rohan Hussain',
        age: 21,
        job: 'Programmer'
    }
]

function addPerson(aname, aage, ajob) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            persons.push({ name: aname, age: aage, job: ajob });
            resolve();
        }, 2000);
    });
}

function personStringify(n) {
    return persons[n].name + ' ' + persons[n].age + ' ' + persons[n].job;
}

function displayPersons() {
    let text = '<ul>';
    let i = 0;
    for (i = 0; i < persons.length; i++) {
        text += '<li>' + personStringify(i) + '</li>';
    }

    text += '</ul>';
    document.body.innerHTML = text;
}

addPerson('Alishba Azam',21,'Audiologist').then(displayPersons())
Unmitigated
  • 76,500
  • 11
  • 62
  • 80

1 Answers1

1

You should pass the function to .then instead of invoking it immediately.

addPerson('Alishba Azam',21,'Audiologist').then(displayPersons)

let persons = [
    {
        name:'Muhammad Rohan Hussain',
        age: 21,
        job: 'Programmer'
    }
]

function addPerson(aname, aage, ajob) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            persons.push({ name: aname, age: aage, job: ajob });
            resolve();
        }, 2000);
    });
}

function personStringify(n) {
    return persons[n].name + ' ' + persons[n].age + ' ' + persons[n].job;
}

function displayPersons() {
    let text = '<ul>';
    let i = 0;
    for (i = 0; i < persons.length; i++) {
        text += '<li>' + personStringify(i) + '</li>';
    }

    text += '</ul>';
    document.body.innerHTML = text;
}

addPerson('Alishba Azam',21,'Audiologist').then(displayPersons);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80