简体   繁体   中英

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.

Many fetch examples use two then s 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM