I'm looking to perform a series of modifications on a document using the VSCode API. The key function in this process is Workspace.applyEdit, which gives back a Thennable
. This is my first encounter with it, and the one returned from this function doesn't behave as I anticipate.
Example 1:
import { window, workspace, WorkspaceEdit, Position } from 'vscode';
// does not work as expected, only inserts once despite logging multiple times
export function applyEditReprex() {
let text = "\ntest\n";
let target = window.activeTextEditor.document.uri;
let positions = [
new Position(10, 1),
new Position(15, 1),
new Position(20, 1)
];
positions.reduce((applyThennable, position) => {
return (
applyThennable.then(() => {
console.info("Making new edit");
let edit = new WorkspaceEdit();
edit.insert(target, position, text);
workspace.applyEdit(edit);
}))
},
Promise.resolve()
).then(() => {
console.info("Finished edits.");
})
}
Only one occurrence of "test" is inserted into the target document at line 12. The log shows:
Making new edit
Making new edit
Making new edit
Finished edits.
Example 2:
My attempt to rewrite the above code as chained calls:
import { window, workspace, WorkspaceEdit, Position } from 'vscode';
export function applyEditReprex2() {
let text = "\ntest\n";
let target = window.activeTextEditor.document.uri;
let positions = [
new Position(10, 1),
new Position(15, 1),
new Position(20, 1)
];
console.info("Making new edit");
let edit = new WorkspaceEdit();
edit.insert(target, positions[0], text);
workspace.applyEdit(edit).then(() => {
console.info("Making new edit");
let edit = new WorkspaceEdit();
edit.insert(target, positions[1], text);
workspace.applyEdit(edit).then(() => {
console.info("Making new edit");
let edit = new WorkspaceEdit();
edit.insert(target, positions[2], text);
workspace.applyEdit(edit).then(() => {
console.info("Finished edits.");
})
})
})
}
Now, 3 instances of "test" are added to the target file, on lines 12, 17, 22.
The log shows:
Making new edit
Making new edit
Making new edit
Finished edits.
Query
Could there be any nuances of reduce
or fat arrow functions that might be causing the difference in behavior between the first snippet and the rewritten version? Alternatively, could the rewritten version not be equivalent to the reduce
method in a significant way?