Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use generators for any asynchronous operation, instead of async/await (or promises) #1

Open
colorful-tones opened this issue Apr 2, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@colorful-tones
Copy link
Owner

Great feedback from @luisherranz

Use generators for any asynchronous operation, instead of async/await (or promises).

    *submitForm( event ) {
      const context = getContext();
      const { ref } = getElement();

      event.preventDefault();

      const formData = new FormData( ref );
      formData.append( 'action', 'submit_feedback' );
      formData.append( 'nonce', context.nonce );
      formData.append( 'postId', context.postId );
      context.isFormProcessing = true;

      try {
        const data = yield fetch( context.ajaxUrl, {
          method: 'POST',
          credentials: 'same-origin',
                body: formData
        }).then( r => r.text() )

        context.hasSuccess = true;
        context.formMessage = "Success!";
      } catch( error ) {
        console.error( 'Error:', error );
        context.hasError = true;
        context.formMessage = "Error!";
      }
    },

This is a requirement for the Interactivity API. In your case, everything works fine, but it could cause issues with the scope.

If you want to keep using promises instead, you need to wrap all the promise callbacks with a withScope(cb) function.

@colorful-tones colorful-tones added the enhancement New feature or request label Apr 2, 2024
@colorful-tones colorful-tones self-assigned this Apr 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant