首页  >  文章  >  web前端  >  关于 Javascript Promise 的有趣事实

关于 Javascript Promise 的有趣事实

Susan Sarandon
Susan Sarandon原创
2024-10-07 20:21:30146浏览

fun facts about Javascript Promises

Promise 始终是异步的

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.resolve() 并不总是创建新的 Promise

如果您传递一个非 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() 不传递值

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)



您可以链接 catch() 来处理特定错误


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;
  })



您可以将await 与非promise 值一起使用


async function demo() {
  const result = await 42; //not a promise
  console.log(result);      
}
demo(); //42


就是这样!感谢您阅读本文。下次见!

以上是关于 Javascript Promise 的有趣事实的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn