您好,登錄后才能下訂單哦!
譯者按: 對于Promise,也許你會用了,卻并不理解;也許你理解了,卻只可意會不可言傳。這篇博客將從3個簡單的視角理解Promise,應該對你有所幫助。
為了保證可讀性,本文采用意譯而非直譯,并且對源代碼進行了大量修改。另外,本文版權歸原作者所有,翻譯僅用于學習。
示例1中,asyncFunc()函數(shù)返回的是一個Promise實例:
// 示例1
function asyncFunc()
{
return new Promise(function(resolve, reject)
{
setTimeout(function()
{
resolve('Hello, Fundebug!');
}, 100);
});
}
asyncFunc()
.then(function(x)
{
console.log(x); // 1秒之后打印"Hello, Fundebug!"
});
1秒之后,Promise實例的狀態(tài)變?yōu)?strong>resolved,就會觸發(fā)then綁定的回調函數(shù),打印resolve值,即"Hello, Fundebug!"。
那么,什么是Promise呢?
示例2可以幫助我們理解阻塞:
// 示例2
function asyncFunc()
{
return new Promise(function(resolve, reject)
{
setTimeout(function()
{
resolve('Hello, Fundebug!');
}, 1000);
});
}
async function main()
{
const x = await asyncFunc(); // (A)
console.log(x); // (B) 1秒之后打印"Hello, Fundebug!"
}
main();
以上代碼是采用Async/Await語法寫的,與示例1完全等價。await的中文翻譯即為"等待",這里可以"望文生義"。因此,相比于使用Promise實現(xiàn),它更加直觀地展示了什么是阻塞。
事實上,使用Promise實現(xiàn)時,也需要等待asyncFunc()執(zhí)行,之后再調用then綁定的回調函數(shù)。因此,調用Promise時,代碼也是阻塞的。
如果某個函數(shù)返回Promise實例,則這個Promise最初相當于一個空白的容器,當函數(shù)執(zhí)行結束時,其結果將會放進這個容器。示例3通過數(shù)組模擬了這個過程:
// 示例3
function asyncFunc()
{
const blank = [];
setTimeout(function()
{
blank.push('Hello, Fundebug!');
}, 1000);
return blank;
}
const blank = asyncFunc();
console.log(blank); // 打印"[]"
setTimeout(function()
{
const x = blank[0]; // (A)
console.log(x); // 2秒之后打印"Hello, Fundebug!"
}, 2000);
開始時,blank為空數(shù)組,1秒之后,"Hello, Fundebug!"被添加到數(shù)組中,為了確保成功,我們需要在2秒之后從blank數(shù)組中讀取結果。
對于Promise,我們不需要通過數(shù)組或者其他變量來傳遞結果,then所綁定的回調函數(shù)可以通過參數(shù)獲取函數(shù)執(zhí)行的結果。
示例4模擬了事件:
// 示例4
function asyncFunc()
{
const eventEmitter = {
success: []
};
setTimeout(function()
{
for (const handler of eventEmitter.success)
{
handler('Hello, Fundebug!');
}
}, 1000);
return eventEmitter;
}
asyncFunc()
.success.push(function(x)
{
console.log(x); // 1秒之后打印"Hello, Fundebug!"
});
調用asyncFunc()之后,sucesss數(shù)組其實是空的,將回調函數(shù)push進數(shù)組,相當于綁定了事件的回調函數(shù)。1秒之后,setTimeout定時結束,則相當于事件觸發(fā)了,這時sucess數(shù)組中已經注冊了回調函數(shù),于是打印"Hello, Fundebug!"。
當Promise成功resolve時,會觸發(fā)then所綁定的回調函數(shù),這其實就是事件。
Fundebug專注于JavaScript、微信小程序、微信小游戲、支付寶小程序、React Native、Node.js和Java實時BUG監(jiān)控。 自從2016年雙十一正式上線,F(xiàn)undebug累計處理了9億+錯誤事件,得到了Google、360、金山軟件、百姓網等眾多知名用戶的認可。歡迎免費試用!
轉載時請注明作者Fundebug以及本文地址:
https://blog.fundebug.com/2017/09/25/3-ways-to-understand-promise/
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。