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中文网其他相关文章!