Promise 的回呼總是在同步程式碼之後執行
const promise = Promise.resolve(); promise.then(() => console.log('async')); console.log('sync'); //sync //async
Promise 每次呼叫時都會傳回一個新的 Promise
const p = Promise.resolve(); const chain = p.then(() => {}); console.log(p === chain); //false
承諾支持無限連結
Promise.resolve(1) .then(value => value + 1) .then(value => value + 1) .then(value => console.log(value)); // 3
您可以包裝使用回調的舊程式碼,以與現代非同步/等待一起使用
function asyncOperation(callback) { setTimeout(() => callback(null, 'Im a callback'), 1000); } const promisified = () => new Promise((resolve, reject) => { asyncOperation((err, result) => { if (err) reject(err); else resolve(result); }); }); promisified().then(result => console.log(result)); // "Im a callback"
如果您傳遞一個非 Promise 值,Promise.resolve() 會將其包裝為已解決的 Promise。但如果你傳遞一個 Promise,它只會回傳相同的 Promise。
const p1 = Promise.resolve('Hello'); const p2 = Promise.resolve(p1); console.log(p1 === p2); // true
Promise.reject('Error!') .then(() => console.log('This will not run')) .then(() => console.log('This will also not run')) .catch(err => console.log('Caught:', err)) .then(() => console.log('This will run'));
finally() 方法不會接收或修改已解析的值。它用於清理資源並運行,無論 Promise 解決還是拒絕。
Promise.resolve('resolved') .then(value => console.log(value)) .finally(() => console.log('Cleanup')) //resolved //cleanup
一旦 Promise 被解決(解決或拒絕),它的狀態就是不可變的。此後無法更改,即使您再次嘗試解決/拒絕它。
const p = new Promise((resolve, reject) => { resolve('First'); resolve('Second'); }); p.then(value => console.log(value)); //"First" (only the first value is used)
Promise.reject('type C error') .catch(err => { if (err === 'type A error') console.log('handle type A'); throw err; }) .catch(err => { if (err === 'type B error') console.log('handle type B'); throw err; }) .catch(err => { if (err === 'type C error') console.log('handle type C'); throw err; })
async function demo() { const result = await 42; //not a promise console.log(result); } demo(); //42
就是這樣!感謝您閱讀本文。下次見!
以上是關於 Javascript Promise 的有趣事實的詳細內容。更多資訊請關注PHP中文網其他相關文章!