A 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()
:
在原先的写法, 当调用一个异步函数的时候, 需要在参数位置指定它的回调函数, 比如异步生成一个语音文件时,指定它的成功和失败的回调 ,代码如下:
1 2 3 4 5 6 7 8 9 |
function successCallback(result) { console.log("Audio file ready at URL: " + result); } function failureCallback(error) { console.error("Error generating audio file: " + error); } createAudioFileAsync(audioSettings, successCallback, failureCallback); |
在现代的javascript 当中, 是返回一个promise
1 |
createAudioFileAsync(audioSettings).then(successCallback, failureCallback); |
上一句代码是以下2句的简写形式:
1 2 |
const promise = createAudioFileAsync(audioSettings); promise.then(successCallback, failureCallback); |
.then 代表promise 确实返回了什么东西, 即使是 null ,
以 opentok-rtc 为例, 它从永久设备取数的方法是调用 swagger-boilerplate的 getKey 方法
在 swagger-boilerplate的 serverPersistence.js 文件
1 2 3 4 |
getKey(aKeyName, aAsObject) { if (!aKeyName) { return Promise.resolve(null); } |
也就是说, 如果没有这个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可以有以上四种状态
如何处理 promise 的成功和失败
1 2 3 4 5 |
promise.then(function(result) { console.log(result); // "Stuff worked!" }, function(err) { console.log(err); // Error: "It broke" }); |
怎么理解这几句 :
1 2 3 4 |
var setPublisherReady; var publisherReady = new Promise(function (resolve) { setPublisherReady = resolve; }); |
变量= resolve是什么意思 ?
参考文章 :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises —– how to use promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise — introduce promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
专门讲 resolve