js异步promise链式调用_js异步promise链式写法解析

promise链式调用通过.then()返回新promise实现异步顺序执行,错误使用.catch()捕获并置于链末尾确保全局捕获;async/await以同步方式简化异步代码,用try/catch处理错误;promise.all适用于并行任务全成功才继续,而promise.race用于响应首个完成的任务。例如链式调用中每个.then()返回新promise决定后续状态,错误在.catch()中集中处理;async函数内用await等待异步结果,结构更清晰;promise.all接收多个promise数组并等全部成功或任一失败,promise.race则取最快完成的结果。

js异步promise链式调用_js异步promise链式写法解析

异步 Promise 链式调用,简单来说,就是让一需要按顺序执行的异步操作,像链条一样一个接一个地执行,避免回调地狱,让代码更清晰易懂。

js异步promise链式调用_js异步promise链式写法解析

Promise 链式调用,让异步操作更像同步代码,可读性更高,也更容易维护。

js异步promise链式调用_js异步promise链式写法解析

Promise 链的本质是,每个.then()方法都会返回一个新的 Promise 对象。这个新的 Promise 对象的状态,取决于.then()中回调函数的返回值。如果回调函数返回一个 Promise,那么新的 Promise 的状态就会和这个返回的 Promise 的状态保持一致;如果回调函数返回一个普通值,那么新的 Promise 的状态就会变成 resolved,并且这个返回值会作为下一个.then()方法的回调函数的参数。

js异步promise链式调用_js异步promise链式写法解析

function asyncTask(value) {   return new Promise((resolve, reject) => {     setTimeout(() => {       const result = value * 2;       console.log(`Task completed with result: ${result}`);       resolve(result);       //reject('Something went wrong'); // 模拟错误     }, 500);   }); }  asyncTask(5)   .then(result => {     console.log('First then:', result);     return asyncTask(result); // 返回一个新的Promise   })   .then(result => {     console.log('Second then:', result);     return asyncTask(result); // 再次返回一个新的Promise   })   .then(result => {     console.log('Third then:', result);     return "Finished!";   })   .then(finalResult => {     console.log('Final result:', finalResult);   })   .catch(error => {     console.error('Error occurred:', error);   })   .finally(() => {     console.log('Chain completed');   }); 

如何处理 Promise 链中的错误?

Promise 链中的错误处理,主要依赖.catch()方法。.catch()方法会捕获链中任何一个 Promise 的 reject 状态。这意味着,如果链中任何一个 Promise 抛出错误,.catch()方法就会被调用。需要注意的是,.catch()方法只会捕获它之前的 Promise 的错误。如果想要处理整个链的错误,应该在链的末尾添加.catch()方法。

asyncTask(5)   .then(result => {     console.log('First then:', result);     return asyncTask(result);   })   .then(result => {     console.log('Second then:', result);     throw new Error("Simulated error in second then"); // 模拟错误     return asyncTask(result);   })   .then(result => {     console.log('Third then:', result);     return "Finished!";   })   .then(finalResult => {     console.log('Final result:', finalResult);   })   .catch(error => {     console.error('Error occurred:', error); // 这里会捕获到 "Simulated error in second then"   })   .finally(() => {     console.log('Chain completed');   });

Async/Await 如何简化 Promise 链?

Async/Await 是 ES2017 引入的语法糖,可以更简洁地处理 Promise。使用 Async/Await 可以让异步代码看起来更像同步代码,从而提高代码的可读性和可维护性。Async 函数会隐式地返回一个 Promise,而 Await 关键字会暂停 Async 函数的执行,直到 Promise 的状态变成 resolved。

async function runTasks() {   try {     let result = await asyncTask(5);     console.log('First result:', result);      result = await asyncTask(result);     console.log('Second result:', result);      result = await asyncTask(result);     console.log('Third result:', result);      console.log('Finished!');   } catch (error) {     console.error('Error occurred:', error);   } finally {     console.log('Tasks completed');   } }  runTasks();

Async/Await 实际上是 Promise 的语法糖,底层依然是 Promise。使用 Async/Await 可以避免.then()方法的嵌套,让代码更易于理解。Async/Await 的错误处理使用 try…catch 语句,也比 Promise 的.catch()方法更直观。

Promise.all 和 Promise.race 的应用场景

Promise.all 和 Promise.race 是处理多个 Promise 的工具函数。Promise.all 接收一个 Promise 数组,并返回一个新的 Promise。这个新的 Promise 会在所有 Promise 都变成 resolved 状态时变成 resolved,或者在任何一个 Promise 变成 rejected 状态时变成 rejected。Promise.race 也接收一个 Promise 数组,并返回一个新的 Promise。这个新的 Promise 会在第一个 Promise 变成 resolved 或 rejected 状态时,就立即变成对应的状态。

  • Promise.all: 适合处理需要并行执行的异步操作,例如同时请求多个 API 接口,等待所有接口都返回数据后,再进行下一步处理。
const promise1 = asyncTask(5); const promise2 = asyncTask(10); const promise3 = asyncTask(15);  Promise.all([promise1, promise2, promise3])   .then(results => {     console.log('All results:', results); // [10, 20, 30]   })   .catch(error => {     console.error('Error occurred:', error);   });
  • Promise.race: 适合处理竞态条件,例如设置一个超时时间,如果异步操作在超时时间内没有完成,就认为操作失败。
const promise = asyncTask(5); const timeout = new Promise((resolve, reject) => {   setTimeout(() => {     reject('Timeout');   }, 1000); });  Promise.race([promise, timeout])   .then(result => {     console.log('Result:', result); // 如果 promise 在 1 秒内完成,则输出结果   })   .catch(error => {     console.error('Error occurred:', error); // 如果超时,则输出 'Timeout'   });

选择使用 Promise.all 还是 Promise.race,取决于具体的业务场景。如果需要等待所有异步操作都完成,就使用 Promise.all;如果只需要等待第一个异步操作完成,或者需要处理竞态条件,就使用 Promise.race。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享