当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Javascript中的神器——Promise

Javascript中的神器——Promise

2019年03月26日  | 移动技术网IT编程  | 我要评论

promise in js

回调函数真正的问题在于他剥夺了我们使用 return 和 throw 这些关键字的能力。而 promise 很好地解决了这一切。

2015 年 6 月, 终于发布了。

ecmascript 是 javascript 语言的国际标准,javascript 是 ecmascript 的实现。es6 的目标,是使得 javascript 语言可以用来编写大型的复杂的应用程序,成为企业级开发语言。

概念

es6 原生提供了 promise 对象。

所谓 promise,就是一个对象,用来传递异步操作的消息。它代表了某个未来才会知道结果的事件(通常是一个异步操作),并且这个事件提供统一的 api,可供进一步处理。

promise 对象有以下两个特点。

(1)对象的状态不受外界影响。promise 对象代表一个异步操作,有三种状态:pending(进行中)、resolved(已完成,又称 fulfilled)和 rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是 promise 这个名字的由来,它的英语意思就是「承诺」,表示其他手段无法改变。

(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。promise 对象的状态改变,只有两种可能:从 pending 变为 resolved 和从 pending 变为 rejected。只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果。就算改变已经发生了,你再对 promise 对象添加回调函数,也会立即得到这个结果。这与事件(event)完全不同,事件的特点是,如果你错过了它,再去监听,是得不到结果的。

有了 promise 对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,promise 对象提供统一的接口,使得控制异步操作更加容易。

promise 也有一些缺点。首先,无法取消 promise,一旦新建它就会立即执行,无法中途取消。其次,如果不设置回调函数,promise 内部抛出的错误,不会反应到外部。第三,当处于 pending 状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。

var promise = new promise(function(resolve, reject) {
 if (/* 异步操作成功 */){
 resolve(value);
 } else {
 reject(error);
 }
});
promise.then(function(value) {
 // success
}, function(value) {
 // failure
});

promise 构造函数接受一个函数作为参数,该函数的两个参数分别是 resolve 方法和 reject 方法。

如果异步操作成功,则用 resolve 方法将 promise 对象的状态,从「未完成」变为「成功」(即从 pending 变为 resolved);

如果异步操作失败,则用 reject 方法将 promise 对象的状态,从「未完成」变为「失败」(即从 pending 变为 rejected)。

基本的 api

promise.resolve()
promise.reject()
promise.prototype.then()
promise.prototype.catch()
promise.all() // 所有的完成
 var p = promise.all([p1,p2,p3]);
promise.race() // 竞速,完成一个即可

进阶

promises 的奇妙在于给予我们以前的 return 与 throw,每个 promise 都会提供一个 then() 函数,和一个 catch(),实际上是 then(null, ...) 函数,

 somepromise().then(functoin(){
  // do something
 });

我们可以做三件事,

1. return 另一个 promise

2. return 一个同步的值 (或者 undefined)

3. throw 一个同步异常 ` throw new eror('');`

1. 封装同步与异步代码

```
new promise(function (resolve, reject) {
 resolve(somevalue);
 });
```

写成

```
promise.resolve(somevalue);
```

2. 捕获同步异常

 new promise(function (resolve, reject) {
 throw new error('悲剧了,又出 bug 了');
 }).catch(function(err){
 console.log(err);
 });

如果是同步代码,可以写成

promise.reject(new error("什么鬼"));

3. 多个异常捕获,更加精准的捕获

somepromise.then(function() {
 return a.b.c.d();
}).catch(typeerror, function(e) {
 //if a is defined, will end up here because
 //it is a type error to reference property of undefined
}).catch(referenceerror, function(e) {
 //will end up here if a wasn't defined at all
}).catch(function(e) {
 //generic catch-the rest, error wasn't typeerror nor
 //referenceerror
});

4. 获取两个 promise 的返回值

1. .then 方式顺序调用
2. 设定更高层的作用域
3. spread

5. finally

任何情况下都会执行的,一般写在 catch 之后

6. bind

somethingasync().bind({})
.spread(function (avalue, bvalue) {
 this.avalue = avalue;
 this.bvalue = bvalue;
 return somethingelseasync(avalue, bvalue);
})
.then(function (cvalue) {
  return this.avalue + this.bvalue + cvalue;
});

或者 你也可以这样

var scope = {};
somethingasync()
.spread(function (avalue, bvalue) {
 scope.avalue = avalue;
 scope.bvalue = bvalue;
 return somethingelseasync(avalue, bvalue);
})
.then(function (cvalue) {
 return scope.avalue + scope.bvalue + cvalue;
});

然而,这有非常多的区别,

  • 你必须先声明,有浪费资源和内存泄露的风险
  • 不能用于放在一个表达式的上下文中
  • 效率更低

7. all。非常用于于处理一个动态大小均匀的 promise 列表

8. join。非常适用于处理多个分离的 promise

```
var join = promise.join;
join(getpictures(), getcomments(), gettweets(),
 function(pictures, comments, tweets) {
 console.log("in total: " + pictures.length + comments.length + tweets.length);
});
```

9. props。处理一个 promise 的 map 集合。只有有一个失败,所有的执行都结束

```
promise.props({
 pictures: getpictures(),
 comments: getcomments(),
 tweets: gettweets()
}).then(function(result) {
 console.log(result.tweets, result.pictures, result.comments);
});
```

10. any 、some、race

```
promise.some([
 ping("ns1.example.com"),
 ping("ns2.example.com"),
 ping("ns3.example.com"),
 ping("ns4.example.com")
], 2).spread(function(first, second) {
 console.log(first, second);
}).catch(aggregateerror, function(err) {
err.foreach(function(e) {
console.error(e.stack);
});
});;

```

有可能,失败的 promise 比较多,导致,promsie 永远不会 fulfilled

11. .map(function mapper [, object options])

用于处理一个数组,或者 promise 数组,

option: concurrency 并发现

map(..., {concurrency: 1});

以下为不限制并发数量,读书文件信息

var promise = require("bluebird");
var join = promise.join;
var fs = promise.promisifyall(require("fs"));
var concurrency = parsefloat(process.argv[2] || "infinity");
var filenames = ["file1.json", "file2.json"];
promise.map(filenames, function(filename) {
 return fs.readfileasync(filename)
 .then(json.parse)
 .catch(syntaxerror, function(e) {
 e.filename = filename;
 throw e;
 })
}, {concurrency: concurrency}).then(function(parsedjsons) {
 console.log(parsedjsons);
}).catch(syntaxerror, function(e) {
 console.log("invalid json in file " + e.filename + ": " + e.message);
});

结果

$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js 1
reading files 35ms
$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js infinity
reading files: 9ms

11. .reduce(function reducer [, dynamic initialvalue]) -> promise

promise.reduce(["file1.txt", "file2.txt", "file3.txt"], function(total, filename) {
 return fs.readfileasync(filename, "utf8").then(function(contents) {
 return total + parseint(contents, 10);
 });
}, 0).then(function(total) {
 //total is 30
});

12. time

.delay(int ms) -> promise
.timeout(int ms [, string message]) -> promise

promise 的实现

async

async 函数与 promise、generator 函数一样,是用来取代回调函数、解决异步操作的一种方法。它本质上是 generator 函数的语法糖。async 函数并不属于 es6,而是被列入了 es7。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网