es6 - promise的基本用法

栏目: JavaScript · 发布时间: 7年前

内容简介:参考:和Promise, then 是一种句式, 用来做一些比较耗时的异步操作。例如:

参考: http://es6.ruanyifeng.com/#docs/promise

和 https://segmentfault.com/a/1190000007535316

Promise, then 是一种句式, 用来做一些比较耗时的异步操作。例如:

new Promise(发送http请求 ).then( 处理返回的response).fail(如果失败了该怎么操作)

我们先看一个例子, promise 是如何被声名和调用的。

安装好node 之后, node 会自动支持es6 的语法。我们直接创建一个 test.js 文件,然后直接 node test.js 即可

my_promise = new Promise(function(resolve, reject){
  console.info("== in promise")
  // 如果该promise 操作成功的话,
  let result = true   //假设成功
  if(result ){
    // 运行成功对应的代码
    resolve()
  }else{
    // 运行失败对应的代码
    reject()
  }
  console.info("== in the last line of promise")
})

my_promise.then(function(){
  console.info("== hi , I am resolve function")
})

运行结果: (可以看出, promise 的 then函数被最后执行的)

$ node test_promise.js
== in promise
== in the last line of promise
== hi , I am resolve function

promise的好处非常多。可以让代码非常简洁。

上面的代码,在es6 中也可以:

1. 把function() {}  写成 => {} 的形式

2. 只保留 promise(function(resolve)), 而不用 promise(function(resolve, error)) 这个形式。(算是省略了对错误的处理)

省略后的样子是这样的:

my_promise = new Promise((resolve) => {
   //...
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

The Cult of the Amateur

The Cult of the Amateur

Andrew Keen / Crown Business / 2007-6-5 / USD 22.95

Amateur hour has arrived, and the audience is running the show In a hard-hitting and provocative polemic, Silicon Valley insider and pundit Andrew Keen exposes the grave consequences of today’s......一起来看看 《The Cult of the Amateur》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试