0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

vscode.window.withProgress()を使った拡張機能を呼び出すときに気をつけること

Last updated at Posted at 2023-03-20

はじめに

vscode.window.withProgress()を呼び出すコマンドをテストしたときに、それは発生した。

TL;DR

awaitを忘れずにつけよう。

テキストを挿入しても内容が更新されない問題

前提として、withProgress()に渡すコールバックの中で、非同期関数を呼び出していた。
そして、その非同期関数を呼び出した後、アクティブなエディタを取得して、選択したテキストの末尾に生成したテキストを挿入していた。

vscode.window.withProgress(
	{
		location: vscode.ProgressLocation.Notification,
		...
	},
	async (progress, token) => {
		return new Promise(async (resolve) => {
			...
			const messages = await Promise.all(...);

			await editor?.edit((textEditor: vscode.TextEditorEdit) => {
				for (const index in selections) {
					const selection = selections[index];
					const text = texts[index];
					const message = messages[index];
					if (selection && text) {
						textEditor.insert(selection.end, "\n" + message);
					}
				}
			});
			resolve(null);
		});
	}
);

これを次のようにテストしたところ、openTextDocument()を呼び出した際に渡したcontentの値から変化せず、strictEqual()が失敗に終わった。

const document = await vscode.workspace.openTextDocument({
  content: selectedText,
});
...
await vscode.commands.executeCommand("extension.command");
...
assert.strictEqual(
  document?.getText(),
  `${selectedText}${newCOntent}`
);

awaitのつけ忘れ

これは自分の凡ミスなのだが、結局のところawaitのつけ忘れだった。

await vscode.window.withProgress(
	{
		location: vscode.ProgressLocation.Notification,
		...
	},
    ...
);

awaitをつけ忘れた理由

参考にしていたコードでは次のようにwithProgress()を呼び出していた。

return vscode.window.withProgress(
	{
		location: vscode.ProgressLocation.Notification,
		...
	},
    ...
);

ただ、僕の場合はこのコードを呼び出し後も処理を行う必要があったため、returnをつけずにそのまま呼び出していた。
デバッグ時にはこの問題に気づかなかったため、テストをしたときに初めて気がついた。

まとめ

vscode.window.withProgress()を呼び出すときは必ずawaitのつけ忘れを確認しましょう。(returnする場合は除く)
あと、テストはきちんと書きましょう。デバッグだけでは気づかない問題に出会うことができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?