您现在的位置是:亿华云 > 域名

盘点JavaScript中的Promise链的高级用法

亿华云2025-10-02 18:43:48【域名】8人已围观

简介大家好,我进阶学习者。一、前言有一系列的异步任务要一个接一个地执行 — 例如,加载脚本。如何写出更好的代码呢?Promise 提供了一些方案来做到这一点。二、案例分析1.运行流程如下它的理念是将 re

大家好,盘点我进阶学习者。盘点

一、盘点前言

有一系列的盘点异步任务要一个接一个地执行 — 例如,加载脚本。盘点如何写出更好的盘点代码呢?

Promise 提供了一些方案来做到这一点。

二、盘点案例分析

1.运行流程如下

它的盘点理念是将 result 通过 .then 处理程序(handler)链进行传递。

//1. 初始 promise 在 1 秒后进行 resolve (*),盘点 //2. 然后 .then 处理程序(handler)被调用 (**)。盘点 //3. 它返回的盘点值被传入下一个 .then 处理程序(handler)(***)。 

之所以这么运行,盘点是盘点因为对 promise.then 的调用会返回了一个 promise,所以可以在其之上调用下一个 .then。盘点

当处理程序(handler)返回一个值时,盘点它将成为该 promise 的 result,所以将使用它调用下一个 .then。

新手常犯的一个经典错误:从技术上讲,也可以将多个 .then 添加到一个 promise 上。但这并不是 promise 链(chaining)。

例 :

let promise = new Promise(function(resolve, reject) {    setTimeout(() => resolve(1), 1000); }); promise.then(function(result) {    alert(result); // 1   return result * 2; }); promise.then(function(result) {    alert(result); // 1   return result * 2; }); promise.then(function(result) {    alert(result); // 1   return result * 2; }); 

在这里所做的只是一个 promise 的几个处理程序(handler)。亿华云他们不会相互传递 result;相反,它们之间彼此独立运行处理任务。

例1:fetch

在前端编程中,promise 通常被用于网络请求。

案例:

将使用 [etch方法从远程服务器加载用户信息。它有很多可选的参数。

let promise = fetch(url); 

执行这条语句,向 url 发出网络请求并返回一个 promise。当远程服务器返回 header(是在 全部响应加载完成前)时,该 promise 用使用一个 response 对象来进行 resolve。

为了读取完整的响应,应该调用 response.text() 方法:当全部文字(full text)内容从远程服务器下载完成后,它会返回一个 promise,该 promise 以刚刚下载完成的这个文本作为 result 进行 resolve。

下面这段代码向 user.json 发送请求,并从服务器加载该文本:

fetch(/article/promise-chaining/user.json)   // 当远程服务器响应时,下面的 .then 开始执行   .then(function(response) {      // 当 user.json 加载完成时,response.text() 会返回一个新的 promise     // 该 promise 以加载的 user.json 为 result 进行 resolve     return response.text();   })   .then(function(text) {      // ...这是远程文件的内容     alert(text); // { "name": "iliakan", "isAdmin": true}   }); 

从 fetch 返回的 response 对象还包括 response.json() 方法,该方法读取远程数据并将其解析为 JSON。在的例子中,这更加方便,所以让切换到这个方法。站群服务器

为了简洁,还将使用箭头函数:

// 同上,但是使用 response.json() 将远程内容解析为 JSON fetch(/article/promise-chaining/user.json)   .then(response => response.json())   .then(user => alert(user.name)); // iliakan, got user name 

现在,让用加载好的用户信息搞点事情。

例如,可以多发一个到 GitHub 的请求,加载用户个人资料并显示头像:

// 发送一个对 user.json 的请求 fetch(/article/promise-chaining/user.json)   // 将其加载为 JSON   .then(response => response.json())   // 发送一个到 GitHub 的请求   .then(user => fetch(`https://api.github.com/users/${ user.name}`))   // 将响应加载为 JSON   .then(response => response.json())   // 显示头像图片(githubUser.avatar_url)3 秒(也可以加上动画效果)   .then(githubUser => {      let img = document.createElement(img);     img.src = githubUser.avatar_url;     img.className = "promise-avatar-example";     document.body.append(img);     setTimeout(() => img.remove(), 3000); // (*)   }); 

这段代码可以工作,具体细节请看注释。但是,这儿有一个潜在的问题,一个新手使用 promise 的典型问题。

请看 (*) 行:如何能在头像显示结束并被移除 之后 做点什么?例如,想显示一个用于编辑该用户或者其他内容的表单。就目前而言,是做不到的。

为了使链可扩展,需要返回一个在头像显示结束时进行 resolve 的 promise。

就像这样:

fetch(/article/promise-chaining/user.json)   .then(response => response.json())   .then(user => fetch(`https://api.github.com/users/${ user.name}`))   .then(response => response.json())   .then(githubUser => new Promise(function(resolve, reject) {  // (*)     let img = document.createElement(img);     img.src = githubUser.avatar_url;     img.className = "promise-avatar-example";     document.body.append(img);     setTimeout(() => {        img.remove();       resolve(githubUser); // (**)     }, 3000);   }))   // 3 秒后触发   .then(githubUser => alert(`Finished showing ${ githubUser.name}`)); 

注:

也就是说,第 (*) 行的 .then 处理程序(handler)现在返回一个 new Promise,源码下载只有在 setTimeout 中的 resolve(githubUser) (**) 被调用后才会变为 settled。链中的下一个 .then 将一直等待这一时刻的到来。

作为一个好的做法,异步行为应该始终返回一个 promise。这样就可以使得之后计划后续的行为成为可能。即使现在不打算对链进行扩展,但之后可能会需要。

三、总结

本文基于JavaScript基础,介绍了Promise 链的高级用法,主要介绍了使用Promise时新手常会出现的几个问题,对这几个问题进行详细的解答。

通过案例的分析,能够更直观的展示。采用JavaScript语言,能够帮助你更好的学习JavaScript。

代码很简单。希望能够帮助你更好的学习。

很赞哦!(4291)