Home > Software design >  How to determine whether the other then() methods can be omitted?
How to determine whether the other then() methods can be omitted?

Time:01-27

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.

CodePudding user response:

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.

  • Related