Promise در js
کاربرد اصلی Promise در js برای sync کردن توابع async هست.
بزارید یک مثال بزنم :
function test() {
setTimeout(function() {
console.log(\'test\');
}, 2000);
}
async function main() {
await test();
console.log(\'here\');
}
main();
در مثال بالا همونطور که میبینید async و await برای تابع test کار نمیکنه و اول here چاپ میشه و بعدش مقدار تست
برای حل این مشکل باید از Promise استفاده کنید
function test() {
return new Promise( function( resolve, reject ) {
setTimeout(function() {
console.log(\'test\');
resolve(\'test\');
}, 2000);
})
}
async function main() {
let a = await test();
console.log(\'here\');
}
main();
اما then چی هست. اگر به صورت async از تابع استفاده کردید. یعنی await رو استفاده نکردید. Promise مثل یک کلاس ساده عمل میکنه که خودتون هم میتونید تعریفش کنید و در پایان Timeout اجرا میشه ...