Javascript Promises

Javascript Promises

2018-11-05 THUDM team Eunbi Choi

  1. Syntax

    new Promise( /* executor */ function(resolve, reject) { ... } );

    executor:

    A function that is passed with the arguments resolve and reject. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively.

  1. 3 states

    A Promise is in one of these states:

    • pending: initial state, neither fulfilled nor rejected.
    • fulfilled: meaning that the operation completed successfully.
    • rejected: meaning that the operation failed.

    A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise‘s then method are called.

  2. Chaining

As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.

  1. Methods

    Promise.all(iterable)

    Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects.

    example:

    let filenames = [‘index.html‘, ‘blog.html‘, ‘terms.html‘];?Promise.all(filenames.map(readFilePromise))  .then(files => {    console.log(‘index:‘, files[0]);    console.log(‘blog:‘, files[1]);    console.log(‘terms:‘, files[2]);  });

    Promise.race(interable)

    Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.

    example:

    function timeout(ms) {  return new Promise((resolve, reject) => {    setTimeout(reject, ms);  });}?Promise.race([readFilePromise(‘index.html‘), timeout(1000)])  .then(data => console.log(data))  .catch(e => console.log("Timed out after 1 second"));

    Promise.reject(reason)

    Returns a Promise object that is rejected with the given reason.

    Promise.resolve(value)

    Returns a Promise object that is resolved with the given value.

  1. Catching and throwing errors

    We should consider all the code inside your then() statements as being inside of a try block. Both return Promise.reject() and throw new Error()will cause the next catch() block to run. A catch() block also catches the runntime error inside then() statement.

  1. Dynamic chains

    Sometimes we want to construct our Promise chain dynamically.

    example:

    function readFileAndMaybeLock(filename, createLockFile) {  let promise = Promise.resolve();?  if (createLockFile) {    promise = promise.then(_ => writeFilePromise(filename + ‘.lock‘, ‘‘))  }?  return promise.then(_ => readFilePromise(filename));}
  1. Running in series

    Sometimes we want to run the Promises in series, or one after the other. There‘s no simple method in Promise, but Array.reduce can help us.

    example:

    let itemIDs = [1, 2, 3, 4, 5];?itemIDs.reduce((promise, itemID) => {  return promise.then(_ => api.deleteItem(itemID));}, Promise.resolve());

    same as:

    Promise.resolve()  .then(_ => api.deleteItem(1))  .then(_ => api.deleteItem(2))  .then(_ => api.deleteItem(3))  .then(_ => api.deleteItem(4))  .then(_ => api.deleteItem(5));
  1. Anti-patterns

    • Recreating callback hell
    • Failure to return
    • Calling .then() multiple times
    • Mixing callbacks and Promises
    • Not catching errors

references:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://medium.com/datafire-io/es6-promises-patterns-and-anti-patterns-bbb21a5d0918

原文地址:https://www.cnblogs.com/THUDM/p/9912352.html

时间: 2024-09-29 19:33:10

Javascript Promises的相关文章

初始JavaScript Promises之二

初始JavaScript Promises之二 上一篇我们初步学习了JavaScript Promises,本篇将介绍Promise如何优雅地进行错误处理以及提升操作node.js风格1的异步方法的逼格,没错就是使用promisify2. 异步编程中的错误处理 人性的.理想的也正如很多编程语言中已经实现的错误处理方式应该是这样: try {     var val = JSON.parse(fs.readFileSync("file.json")); }catch(SyntaxErro

转:JavaScript Promises相当酷:一种有趣的方案库

许多的语言,为了将异步模式处理得更像平常的顺序,都包含一种有趣的方案库,它们被称之为promises,deferreds,或者futures.JavaScript的promises ,可以促进关注点分离,以代替紧密耦合的接口. 本文讲的是基于Promises/A 标准的JavaScript promises.[http://wiki.commonjs.org/wiki/Promises/A]Promise的用例: 执行规则 多个远程验证 超时处理 远程数据请求 动画 将事件逻辑从应用逻辑中解耦

初识JavaScript Promises

JavaScript有很多槽点,嵌套回调怕是千夫所指. 很久之前,我一直使用async来处理JavaScript异步编程中的嵌套回调问题.当然我也大概的了解过一些其它旨在解决这些问题的类库,诸如EventProxy.Jscex.StepJS.thenjs. 当我第一次看到Promises规范的时候,我根本无法理解它所带来的好处.譬如每个初次学习Promises的人都见过如下的示例代码: //callbacks function callback(err, value){ if(err){ //

Javascript Promises 介绍

什么是 Promises Promises是一种关于异步编程的规范,目的是将异步处理对象和处理规则进行规范化,为异步编程提供统一接口. 传统的回调函数 说到JavaScript的异步编程处理,通常我们会想到回调函数,如下面的代码: getFileAsync("1.txt", function(error, result){ if(error){ throw error; } // 取得成功时的处理 }); 上面的代码定义了一个获取文件内容的函数,读取完成后回调用传入的回调函数,对于下面

翻译:JavaScript Promises and AngularJS $q Service

原文:http://www.webdeveasy.com/javascript-promises-and-angularjs-q-service/ 原文时间:2014年9月30号 一个promise(延缓)是处理异步开发简单而强大的方法.CommonJS 维基百科列出了几个promise模式的实施提议.AngularJS自己的promise实现方法是受kris Kowal's Q的方法启发的.在这篇文章中我会介绍promises,它的目的和怎么通过AngularJS $q的promise服务开发

异步编程之Javascript Promises 规范介绍

什么是 Promises Promises是一种关于异步编程的规范,目的是将异步处理对象和处理规则进行规范化,为异步编程提供统一接口. 传统的回调函数 说到JavaScript的异步编程处理,通常我们会想到回调函数,如下面的代码: getFileAsync("1.txt", function(error, result){      if(error){          throw error;      }     // 取得成功时的处理 }); 上面的代码定义了一个获取文件内容的

[Javascript] Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()

The Promise.allSettled() method accepts an array (or any other iterable) of promises as a parameter. It returns a Promise object that is fulfilled with an array of settlement objects. Each settlement object describes the settlement of the correspondi

NodeJS Multiple Callback解决之使用Q Promises

在上一篇<Javascript Promises模式--相当酷的Callback Hell终结者>我们介绍了Javascript的Promise模式,接着我们就把Javascript Promise用到我们的代码中. JavaScript Promise库 Q 之前试着用过Q,但是没有成功.或者说,在那时候不需要用上Q,所以没有深究.现在抱着学习的态度,重新试了一下,效果还不错. A tool for making and composing asynchronous promises in

JavaScript及其异步实现

由于javascript本身是单线程模型,这里主要通过Callbacks,Listeners,Control Flow Libraries ,Promises四种方式来实现异步操作. Reference:            1.JavaScript异步编程的四种方法(转)           2.JavaScript Promises 一.Callbacks(函数回调) 让我们首先以函数回调方式来开头,这种方式也是最基本,同时也是大家都知道的异步实现方法. 现在我们有两个函数:Functio