Skip to content

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

@colorful-tones

Description

@colorful-tones

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.

Metadata

Metadata

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions