Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to determine whether the other then() methods can be omitted?

The following codes illustrate a form which allows optionally pasting the value from the clipboard before automatically submitting. It uses two then() methods. Please use Chrome to test it because Firefox does not support it yet.

const input = document.querySelector('input'),
      submitButton = document.querySelector('button[type="submit"]'),
      pasteAndSubmitButton = document.querySelector('button[type="button"]');

pasteAndSubmitButton.addEventListener('click', function ()
{
    navigator.clipboard.readText()
        .then(clipText => input.value = clipText)
        .then(() => submitButton.click());
});
<form>
    Address: <input type="text" name="address" required>
    <button type="submit">Submit</button>
    or
    <button type="button">Paste and Submit</button>
</form>

I’m wondering whether it is safe to omit the second then() method and move the code inside into the first one like this:

navigator.clipboard.readText()
    .then(clipText =>
    {
        input.value = clipText;
        submitButton.click();
    });

My test shows that the result is the same. But I’m just not sure whether it is always safe to omit the second then() method because the fetch examples I have seen so far use two then() methods.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Many fetch examples use two thens because two promises are involved: one to get the response header, and one to read the body. In other words, both fetch and typical follow-up methods like Response.text() return a promise. Two promises aren’t involved here, so you only need one then.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading