function greeting(name) {
console.log(`Сайн байна уу, ${name}!`);
}
function processUserInput(callback) {
const name = "Болд";
callback(name);
}
processUserInput(greeting); // Гаралт: "Сайн байна уу, Болд!"
console.log("Эхлэх...");
setTimeout(() => {
console.log("3 секундын дараа!");
}, 3000); // 3000ms = 3 секунд
console.log("Төгсөх...");
Гаралт:
"Эхлэх..."
"Төгсөх..."
// 3 секундын дараа:
"3 секундын дараа!"
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`${count} секунд өнгөрлөө`);
if (count >= 5) {
clearInterval(intervalId); // Зогсоох
console.log("Дууслаа!");
}
}, 1000);
function readFile(path, callback) {
// Файл уншиж байгаа дүрслэл
setTimeout(() => {
const content = "Файлын агуулга";
callback(null, content);
}, 2000);
}
function processContent(content, callback) {
// Контент боловсруулж байгаа дүрслэл
setTimeout(() => {
const processed = content.toUpperCase();
callback(null, processed);
}, 1000);
}
function saveFile(content, callback) {
// Файл хадгалж байгаа дүрслэл
setTimeout(() => {
console.log("Файл хадгалагдлаа");
callback(null, true);
}, 1500);
}
readFile('input.txt', (error, content) => {
if (error) {
console.error('Уншихад алдаа:', error);
return;
}
processContent(content, (error, processed) => {
if (error) {
console.error('Боловсруулахад алдаа:', error);
return;
}
saveFile(processed, (error, success) => {
if (error) {
console.error('Хадгалахад алдаа:', error);
return;
}
console.log('Амжилттай дууслаа!');
});
});
});
const readFilePromise = () => {
return new Promise((resolve, reject) => {
readFile('input.txt', (error, content) => {
if (error) reject(error);
else resolve(content);
});
});
};
// Ашиглах
readFilePromise()
.then(content => processContent(content))
.then(processed => saveFile(processed))
.then(() => console.log('Амжилттай!'))
.catch(error => console.error('Алдаа:', error));
const myPromise = new Promise((resolve, reject) => {
// Асинхрон код
if (/* амжилттай */) {
resolve(value);
} else {
reject(error);
}
});
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'Data' };
resolve(data);
// эсвэл
// reject(new Error('Алдаа гарлаа'));
}, 2000);
});
fetchData
.then(data => {
console.log('Амжилттай:', data);
})
.catch(error => {
console.error('Алдаа:', error);
})
.finally(() => {
console.log('Үргэлж ажиллана');
});
fetchUserData(userId)
.then(user => fetchUserPosts(user.id))
.then(posts => fetchPostComments(posts[0].id))
.then(comments => {
console.log(comments);
})
.catch(error => {
console.error('Алдаа гарлаа:', error);
});
Promise.all([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
])
.then(([users, posts, comments]) => {
// Бүх promise амжилттай
});
Promise.race([
fetch('/api/fast'),
fetch('/api/slow')
])
.then(firstResult => {
// Хамгийн түрүүнд биелсэн
});
setTimeout(() => {
console.log("Done!");
}, 2000);
new Promise(resolve => {
setTimeout(() => {
resolve("Done!");
}, 2000);
});
Тоологч үүсгэ:
Тоологч үүсгэ:
setTimeout(() => {
let count = 0;
const timer = setInterval(() => {
count++;
console.log(count);
if (count >= 10) {
clearInterval(timer);
console.log('Дууслаа!');
}
}, 1000);
}, 3000);
Дараах үйлдлүүдийг Promise chain ашиглан хийнэ:
Дараах үйлдлүүдийг Promise chain ашиглан хийнэ:
function getUserId() {
return new Promise(resolve => {
setTimeout(() => resolve(12345), 1000);
});
}
function getOrders(userId) {
return new Promise(resolve => {
setTimeout(() => {
resolve([
{ id: 1, amount: 100 },
{ id: 2, amount: 200 }
]);
}, 1000);
});
}
getUserId()
.then(userId => getOrders(userId))
.then(orders => {
const total = orders.reduce(
(sum, order) => sum + order.amount, 0
);
console.log('Нийт дүн:', total);
})
.catch(error => console.error(error));
Promise.all ашиглан 3 API дуудалтыг зэрэг хийх:
Бүгд амжилттай биелэх ёстой.
Promise.all ашиглан 3 API дуудалтыг зэрэг хийх:
Бүгд амжилттай биелэх ёстой.
const getUser = () => new Promise(resolve =>
setTimeout(() => resolve({ id: 1, name: 'Болд' }), 1000)
);
const getCart = () => new Promise(resolve =>
setTimeout(() => resolve({ items: ['Бараа 1', 'Бараа 2'] }), 1500)
);
const getDelivery = () => new Promise(resolve =>
setTimeout(() => resolve({ address: 'Улаанбаатар' }), 800)
);
Promise.all([getUser(), getCart(), getDelivery()])
.then(([user, cart, delivery]) => {
console.log('Бүх мэдээлэл:', { user, cart, delivery });
})
.catch(error => console.error('Алдаа:', error));
API дуудалтын алдааг шийдвэрлэх:
API дуудалтын алдааг шийдвэрлэх:
function fetchWithRetry(url, retries = 3) {
return new Promise((resolve, reject) => {
function attempt(attemptsLeft) {
fetch(url)
.then(resolve)
.catch(error => {
console.log(`Үлдсэн оролдлого: ${attemptsLeft}`);
if (attemptsLeft === 0) {
reject(new Error(`Алдаа: ${error.message}`));
return;
}
setTimeout(() => {
attempt(attemptsLeft - 1);
}, 1000);
});
}
attempt(retries);
});
}
// Ашиглах
fetchWithRetry('https://api.example.com/data')
.then(response => console.log('Амжилттай:', response))
.catch(error => console.error('Эцсийн алдаа:', error));
Асуулт байна уу?