码迷,mamicode.com
首页 > 其他好文 > 详细

Using promises

时间:2017-09-09 00:49:30      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:rtc   blank   turn   nal   cts   success   method   closed   time   

Using promises

  过去,异步方法这样写:

技术分享
function successCallback(result) {
  console.log("It succeeded with " + result);
}

function failureCallback(error) {
  console.log("It failed with " + error);
}

doSomething(successCallback, failureCallback);
View Code

  使用promise后,异步方法这样写:

技术分享
let promise = doSomething(); 
promise.then(successCallback, failureCallback);
View Code

  promise模式有以下几个好处:

  1、回调方法永远在下一帧后才会调用。即使当前帧已完成。

  2、可以通过串连.then,设置多个回调。

 

  promise模式可以用于解决死亡金字塔问题:

技术分享
doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log(‘Got the final result: ‘ + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);
View Code
技术分享
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);
View Code

 

  catch(failureCallback) 是 then(null, failureCallback) 的简单写法

  使用new Promise((resolve, reject)=>{})创建 Promise。Basically, the promise constructor takes an executor function that lets us resolve or reject a promise manually

技术分享
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);
View Code
技术分享
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‘);
});
View Code

 

  Promise.resolve() and Promise.reject() are shortcuts to manually create an already resolved or rejected promise respectively

  以下两段代码均为reduce应用。用于串于执行异步或同步调用。

技术分享
[func1, func2].reduce((p, f) => p.then(f), Promise.resolve());
View Code
技术分享
Promise.resolve().then(func1).then(func2);
View Code

 

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

 

Using promises

标签:rtc   blank   turn   nal   cts   success   method   closed   time   

原文地址:http://www.cnblogs.com/tekkaman/p/7496790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!