Home > OS >  Made Javascript running arguments function sequential in order
Made Javascript running arguments function sequential in order

Time:01-18

// Send AJAX request to route
function fetch_post(key, ...values){
    const formData = new FormData();
    for (let value of values){
        formData.append(key, value)
    }
    fetch('/settings', {
        method: 'post',
        body: formData
    });
}

In this attribute-value:

onchange="fetch_post(this.name, this.value); location.reload();"

I want location.reload() runs when the fetch_post running is finished.

CodePudding user response:

You want location.reload() runs when the fetch_post running is finished.

then is promise chaining.

If fetch is successfully invoked, the code is executed.


    fetch('/settings', {
        method: 'post',
        body: formData
    })
    .then((res) => {
        console.log(res);
        location.reload();
    });

Or, If you just want to run it when the function is over, use it as the code below.


function fetch_post(key, ...values){
    const formData = new FormData();
    for (let value of values){
        formData.append(key, value)
    }
    fetch('/settings', {
        method: 'post',
        body: formData
    });
    location.reload();
}

CodePudding user response:

Just add location.reload() in then function of fetch like this:

// Send AJAX request to route
function fetch_post(key, ...values){
    const formData = new FormData();
    for (let value of values){
        formData.append(key, value)
    }
    fetch('/settings', {
        method: 'post',
        body: formData
    }).then((data) => {
        location.reload(); <----- this
    }).catch((err)=> {
    }).finally(() => {
    });
}

Hope this help!

  • Related