Invoke the Organize Imports function using code and then proceed to save the updated file automatically

My current task involves:

async function doItAll(ownEdits: Array<TextEdit>) {
    const editor: TextEditor = await getEditor();
    applyOwnChanges(editor, ownEdits);
    await commands.executeCommand('editor.action.organizeImports',
        editor.document.uri.path);
    await editor.document.save();
}

While everything is functioning correctly, the save operation is being executed before organizeImports completes, resulting in a dirty editor when the imports are modified.

I have meticulously checked for any missing await keywords, but it seems like they are not being recognized. Is this possibly a bug or am I overlooking something in my approach?

Answer №1

It's worth noting that the organizeImports command may give the appearance of returning before actually updating the document.

To work around this issue, consider utilizing the onDidChangeTextDocument event to detect when organizeImports has completed and your document is ready for saving.

const listener = vscode.workspace.onDidChangeTextDocument(change => {
  if (change.document.uri.path === currentEditor.document.uri.path) {
    change.document.save();
    listener.dispose();
  }
});

Answer №2

executeCommand is a Thenable object. Therefore, the save() method needs to be placed inside the thenable function.

vscode.commands.executeCommand('editor.action.organizeImports', editor.document.uri.path).then(function(){
        await editor.document.save();
});

If the save operation still occurs before organizeImports completes, consider using setTimeout(function(){....}, T) to delay the save operation.

 vscode.commands.executeCommand('editor.action.organizeImports', editor.document.uri.path).then(function(){
       setTimeout(function(){
            await editor.document.save();
       }, 500);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing asynchronous and synchronous functions in Node.js side by side

In this module, when x is returned as undefined, it raises concerns. const si = require('systeminformation'); async function systemData() { try { let data = await si.system() return { manufacturer: data.manufacturer, model: ...

Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below. This code is using rxjs 5.0.3 with tsc 2.1.5 import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject ...

When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the c ...

Display issues with deeply nested components

I'm facing an issue with displaying the third nested component. Expected: Hello App Component Hello Nest-A Component Hello Nest-1 Component Hello Test-Z Component Actual: Hello App Component Hello Nest-A Component Hello Nest-1 Component Why ...

What causes the unexpected behavior of the rxjs share operator when used with an observable in a service?

I attempted to utilize the rxjs share operator in two distinct manners. Implementing it in the component Component: constructor() { const obs1 = interval(1000).pipe( tap(x => console.log('processing in comp1')), map(x => x ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

The issue of Angular 9 not recognizing methods within Materialize CSS modals

I am currently working on an Angular 9 application and have integrated the materialize-css 1.0 library to incorporate a modal within my project. Everything works smoothly in terms of opening and instantiating the modal. However, I have encountered an issue ...

Problems with updating HTML/Typescript in Visual Studio and Chrome are causing frustration

While working on my company's application locally and making HTML/TS changes, I am facing an issue. Whenever I save/hot reload and refresh the browser, no changes seem to take effect. I've tried stopping debugging, building/rebuilding, and runni ...

Defining generic types for subclasses inheriting from an abstract class containing type variables in TypeScript

Within my abstract class Base, I utilize a type variable <T> to define the type for the class. I have numerous derived classes that explicitly specify the type, like class Derived extends Base<string> {...} I aim to have a variable (or an arra ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

Ways to access the new value of a cell in a Material UI Datagrid through the use of GridCellParams

When trying to access the newly modified value in a cell using the GridCellParams interface, I am faced with the issue that the 'value' property only provides me with the previous value of the cell. This asynchronous behavior is not ideal for my ...

What is the best way to transform a JS const into TSX within a Next.js application?

Exploring the code in a captivating project on GitHub has been quite an adventure. The project, located at https://github.com/MaximeHeckel/linear-vaporwave-react-three-fiber, showcases a 3D next.js application that enables 3D rendering and animation of mes ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

The pipe in Angular 2.0.0 was not able to be located

Error: Issue: Template parse errors: The 'datefromiso' pipe is not recognized Custom Pipe: import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'datefromiso' }) export class DateFromISO implements P ...

Angular 2: Capturing scroll events from the parent element within a Directive

One of the challenges I encountered is with a directive called [appInvalidField] that functions like a custom tooltip for validation purposes. To ensure it appears above everything else within dialogs, I attach it to the body and position it near the relev ...

Tips for modifying the text color of a div that is being iterated through using ngFor

I am facing an issue with a div that is being looped using ngFor. What I want to achieve is when a user clicks on one of the divs in the loop, only that particular div should change its text color. If another div is clicked, it should change color while th ...

Exploring the power of Vue 3 and Vuex with Typescript to access class methods

Can Vuex state be used to access class methods? For example, in this scenario, I am attempting to invoke fullName() to show the user's formatted name. TypeError: store.state.user.fullName is not a function Classes export class User { constructo ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

Including a screenshot in the allure report

I am struggling to figure out how to include a screenshot in my allure report using cypress and mocha-allure-reporter. Despite the report generating correctly, I have not been able to find any examples or guidance on how to set it up and add screenshots ...

The inner map function isn't being executed in Rxjs

I have written some code that utilizes two pipes to load a product instance along with its playlist. In case there is an error while loading the playlist, the property is set to null: getProduct(productId: number): Observable<ProductDTO> { retur ...