@kiyotd/wait-define
v1.0.1
Published
An asynchronous function that waits until a property of an object is defined.
Readme
wait-define
An asynchronous function that waits until a property of an object is defined.
Table of Contents
Installation
Node.js / bundler
# Using npm
npm install @kiyotd/wait-define
# Using yarn
yarn add @kiyotd/wait-defineThe package ships both ESM (dist/index.mjs) and CommonJS (dist/index.cjs) builds along with type definitions, and the right one is picked automatically through the exports field in package.json.
Browser (without a bundler)
The ESM build is a standalone, browser-ready file. Pick whichever delivery method fits your project.
Option A. Download from GitHub Releases
Grab wait-define.mjs from the latest release and drop it under your site (e.g. js/wait-define.mjs).
# Always-latest URL
https://github.com/kiyotd/wait-define/releases/latest/download/wait-define.mjsOption B. Load from a CDN
<script type="module">
import { waitDefine } from "https://cdn.jsdelivr.net/npm/@kiyotd/wait-define/dist/index.mjs";
</script>unpkg.com and esm.sh work the same way.
Usage
Basic Example
If you wait until window.hello is defined:
import { waitDefine } from '@kiyotd/wait-define';
document.addEventListener('DOMContentLoaded', async () => {
console.log('waiting for window.hello ...');
setTimeout(() => {
// @ts-ignore
window.hello = 'world';
}, 2500);
waitDefine('hello', window, 100, 2000)
.then(() => {
console.log('window.hello is defined!');
})
.catch((error) => {
console.error('An error occurred:', error);
});
});In the above example, window.hello is defined after 2500ms, but an error occurs because the monitoring time is only up to 2000ms.
Browser Example
A self-contained HTML page using the locally-hosted ESM build:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wait-define example</title>
</head>
<body>
<p id="status">Waiting for window.hello ...</p>
<script type="module">
import { waitDefine } from "./js/wait-define.mjs";
const status = document.getElementById("status");
setTimeout(() => {
window.hello = "world";
}, 1000);
waitDefine("hello", window, 100, 3000)
.then(() => {
status.textContent = "window.hello is defined!";
})
.catch((error) => {
status.textContent = `An error occurred: ${error.message}`;
});
</script>
</body>
</html>Swap ./js/wait-define.mjs for a CDN URL (see Installation) if you don't want to host the file yourself.
Advanced Examples
Waiting for a nested property
import { waitDefine } from '@kiyotd/wait-define';
// Create an object with a nested structure
const data = { user: {} };
// Set the nested property after a delay
setTimeout(() => {
data.user.profile = { name: 'John', age: 30 };
}, 1000);
// Wait for the nested property to be defined
waitDefine('profile', data.user, 100, 2000)
.then(() => {
console.log('User profile is now available:', data.user.profile);
})
.catch((error) => {
console.error('Failed to get user profile:', error);
});Using with async/await
import { waitDefine } from '@kiyotd/wait-define';
async function loadData() {
try {
// Wait for API data to be loaded into window.apiData
await waitDefine('apiData', window, 100, 5000);
// Now we can safely use window.apiData
const userData = window.apiData.users;
console.log('User data loaded:', userData);
return userData;
} catch (error) {
console.error('Failed to load API data:', error);
throw error;
}
}
// Call the async function
loadData().then(data => {
// Process the data
});API Reference
Arguments
| Name | Type | Description |
|----------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| propertyName | string | The property name to wait for definition |
| obj | any | Object waiting for property definition |
| interval_ms | number | Interval (in milliseconds) to check definitions. Default is 100 milliseconds. |
| timeout_ms | number | Time (in milliseconds) to exit wait and throw an error. If not specified, waits indefinitely until the definition is confirmed. |
Returns
Returns a Promise that resolves when the property is defined. If a timeout is specified and the property is not defined within that time, the Promise will be rejected with a timeout error.
TypeScript Support
This library is written in TypeScript and includes type definitions. No additional installation is needed for TypeScript support.
// Type definition
function waitDefine(
propertyName: string,
obj: any,
interval_ms?: number,
timeout_ms?: number
): Promise<void>;License
MIT
