javascript promise 详解

Promise is an object representing the eventual completion or failure of an asynchronous operation

promise 代表一个异步事件的完成或失败。

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

本质上, promise 是一个 被返回的object ,  在这个object 内可以附加回调函数 ,以代替原来的在函数中指定回调函数 。


Imagine a function, createAudioFileAsync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs.

Here’s some code that uses createAudioFileAsync():

在原先的写法,  当调用一个异步函数的时候, 需要在参数位置指定它的回调函数, 比如异步生成一个语音文件时,指定它的成功和失败的回调 ,代码如下:


在现代的javascript 当中, 是返回一个promise



.then 代表promise 确实返回了什么东西, 即使是 null ,

以 opentok-rtc 为例, 它从永久设备取数的方法是调用 swagger-boilerplate的 getKey 方法

在 swagger-boilerplate的 serverPersistence.js 文件

也就是说, 如果没有这个key , 返回 null , 但这并不会触发 promise 的 catch , 而是触发 resolve, 因为确实返回了什么

promise 和事件(event) 有点像, 但是, promise 只能成功或者失败一次, event可以发生多次。

A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.

If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

promise 可以在发生之后很久被调用, event不可以

A promise can be:

  • fulfilled – The action relating to the promise succeeded
  • rejected – The action relating to the promise failed
  • pending – Hasn’t fulfilled or rejected yet
  • settled – Has fulfilled or rejected


如何处理 promise 的成功和失败

怎么理解这几句 :

变量= resolve是什么意思 ?




参考文章 :   —– how to use promise    — introduce promise

专门讲  resolve