JavaScript中的promise的then()方法以及链式调用

一个promise就是一个代表了异步操作最终完成或者失败的结果对象。

Promise 本质上是一个绑定了回调的对象,而不是将回调传进函数内部

假设存在一个名为 createAudioFileAsync() 的函数,这个函数异步地生成声音文件,在声音文件创建成功或者创建失败后执行回调函数。

以下为使用createAudioFileAsync()的示例:

// 成功的回调函数
function successCallback(result) {
  console.log("声音文件创建成功: " + result);
}

// 失败的回调函数
function failureCallback(error) {
  console.log("声音文件创建失败: " + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback)

如果函数返回Promise 对象:

const promise = createAudioFileAsync(audioSettings); 
promise.then(successCallback, failureCallback);
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);

我们把这个称为异步函数调用,这种形式有若干优点。

约定

不同于老式的传入回调,在应用 Promise 时,我们将会有以下约定:

  • 在 JavaScript 事件队列的当前运行完成之前,回调函数永远不会被调用。
  • 通过 .then 形式添加的回调函数,甚至都在异步操作完成之后才被添加的函数,都会被调用,如上所示。
  • 通过多次调用 .then,可以添加多个回调函数,它们会按照插入顺序并且独立运行。

因此,Promise 最直接的好处就是链式调用。 

链式调用

一个常见的需求就是连续执行两个或者多个异步操作,这种情况下,每一个后来的操作都在前面的操作执行成功之后,带着上一步操作所返回的结果开始执行。我们可以通过创造一个 Promise chain 来完成这种需求。

见证奇迹的时刻:then 函数会返回一个新的 Promise,跟原来的不同: 

const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);

或者 

const promise2 = doSomething().then(successCallback, failureCallback);

第二个对象(promise2)不仅代表doSomething()函数的完成,也代表了你传入的 successCallback 或者failureCallback 的完成,这也可能是其他异步函数返回的 Promise。这样的话,任何被添加给 promise2 的回调函数都会被排在 successCallback 或 failureCallback 返回的 Promise 后面。

基本上,每一个 Promise 代表了链式中另一个异步过程的完成。

在过去,做多重的异步操作,会导致经典的回调地狱:

doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

 通过新式函数,我们把回调绑定到被返回的 Promise 上代替以往的做法,形成一个 Promise 链:

doSomething().then(function(result) {
  return doSomethingElse(result);
})
.then(function(newResult) {
  return doThirdThing(newResult);
})
.then(function(finalResult) {
  console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);

then里的参数是可选的,catch(failureCallback) 是 then(null, failureCallback) 的缩略形式。如下所示,也可以用 arrow function(箭头函数)来表示:

doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);

注意:如果想要在回调中获取上个 Promise 中的结果,上个 Promise 中必须要返回结果。(使用 () => x 比() => { return x; } 更简洁一点).

Catch 的后续链式操作

在一个失败操作(即一个 catch)之后可以继续使用链式操作,即使链式中的一个动作失败之后还能有助于新的动作继续完成。请阅读下面的例子:

new Promise((resolve, reject) => {
    console.log('Initial');

    resolve();
})
.then(() => {
    throw new Error('Something failed');
        
    console.log('Do this');
})
.catch(() => {
    console.log('Do that');
})
.then(() => {
    console.log('Do this whatever happened before');
});

输出结果如下:

Initial

Do that

Do this whatever happened before

注意,由于“Something failed”错误导致了拒绝操作,所以“Do this”文本没有被输出。

发布了55 篇原创文章 · 获赞 32 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_41542894/article/details/86565027