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

开发 前端
有一系列的异步任务要一个接一个地执行 — 例如,加载脚本。如何写出更好的代码呢?Promise 提供了一些方案来做到这一点。

一、前言

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

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。

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

责任编辑:华轩 来源: 前端进阶学习交流
相关推荐

2021-08-10 09:57:27

JavaScriptPromise 前端

2015-07-23 11:59:27

JavascriptPromise

2022-07-03 08:06:40

JavaScript语言代码

2021-02-07 22:59:55

JavaScript编程方法链

2021-09-04 07:56:44

Pythonos模块

2011-05-25 14:23:55

Javascriptthis

2021-10-09 07:10:30

JavaScriptBigIn函数

2021-10-09 07:10:31

JavaScript对象Python

2009-06-17 15:01:07

javascript

2023-09-15 15:31:23

异步编程Promise

2017-03-10 10:16:37

PythonRequests库

2021-06-07 09:44:10

JavaScript开发代码

2022-04-04 09:12:18

Python内置函数

2022-10-11 23:50:43

JavaScript编程Promise

2011-05-12 18:26:08

Javascript作用域

2021-08-31 10:01:04

JavaScript函数属性

2021-06-15 10:01:27

JavaScript数组遍历Entries

2021-09-14 07:26:25

JavaScript迭代对象

2021-09-03 10:00:00

JavaScript迭代对象

2021-07-16 07:57:35

JavaScriptEval函数
点赞
收藏

51CTO技术栈公众号