AsyncDisposableStack.prototype.adopt()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Phương thức adopt() của các instance AsyncDisposableStack đăng ký một giá trị không triển khai giao thức async disposable vào ngăn xếp bằng cách cung cấp một hàm disposer tùy chỉnh.
Xem DisposableStack.prototype.adopt() để biết thông tin chung về phương thức adopt().
Cú pháp
adopt(value, onDispose)
Tham số
Giá trị trả về
Cùng value đã được truyền vào.
Ngoại lệ
TypeError-
Ném ra nếu
onDisposekhông phải là một hàm. ReferenceError-
Ném ra nếu ngăn xếp đã bị hủy.
Ví dụ
>Sử dụng adopt()
Hàm này tạo một file handle (là một Node.js FileHandle), sẽ được đóng khi hàm hoàn thành. Giả sử file handle không triển khai giao thức async disposable (thực tế thì có), vì vậy chúng ta dùng adopt() để đăng ký nó vào ngăn xếp. Vì phương thức handle.close() trả về một promise, chúng ta cần dùng AsyncDisposableStack để việc hủy được chờ (await).
async function readFile(path) {
await using disposer = new AsyncDisposableStack();
const handle = disposer.adopt(
await fs.open(path),
async (handle) => await handle.close(),
);
const data = await handle.read();
// The handle.close() method is called and awaited here before exiting
return data;
}
Đặc tả
| Specification |
|---|
| ECMAScript Async Explicit Resource Management> # sec-asyncdisposablestack.prototype.adopt> |