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 支持无限链接
Promise.resolve(1) .then(value => value 1) .then(value => value 1) .then(value => console.log(value)); // 3
您可以包装使用回调的旧代码,以与现代 async/await 一起使用
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 中。但如果你传递一个承诺,它只会返回相同的承诺。
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
就是这样!感谢您阅读本文。下次再见!
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3