[英]Trying to uderstand Thennables in the VSCode API. Are these equivalent typescript code snippets?
我想對 VSCode API 中的文檔執行一系列編輯。 使這一切發生的函數是Workspace.applyEdit ,它返回一個Thennable
。 這是我第一次使用這些,並且此函數返回的函數與我預期的不一樣。
import { window, workspace, WorkspaceEdit, Position } from 'vscode';
//doesn't work, only makes first insertion, althouh all info text prints
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.");
})
}
在第 12 行的目標文檔中只出現了一個“test”實例。日志報告:
Making new edit
Making new edit
Making new edit
Finished edits.
我嘗試將上面展開為直鏈調用:
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.");
})
})
})
}
目標文件中的第 12、17、22 行出現了 3 個“test”實例。
日志報告:
Making new edit
Making new edit
Making new edit
Finished edits.
是否有任何我可能不知道的reduce
或胖箭頭函數的復雜性可能導致第一個片段的行為與展開版本不同? 或者另一種方式:展開的版本在某些重要方面不等同於reduce
嗎?
您忘記從承諾的 .then .then()
回調中return
thenable 對象,這對於承諾鏈接至關重要:
positions.reduce((prevPromise, position) => {
return prevPromise.then(() => {
console.info("Making new edit");
const edit = new WorkspaceEdit();
edit.insert(target, position, text);
const applyThenable = workspace.applyEdit(edit);
return applyThenable;
// ^^^^^^^^^^^^^^^^^^^^
});
}, Promise.resolve())
順便說一句,我從您鏈接的文檔中對 API 的理解是,您應該只制作一個帶有多個插入的WorkspaceEdit
:
const positions = [
new Position(10, 1),
new Position(15, 1),
new Position(20, 1)
];
const edit = new WorkspaceEdit();
for (const position in positions) {
edit.insert(target, position, text);
}
workspace.applyEdit(edit).then(() => {
console.info("Finished multi-edit.");
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.