LazyMan的Promise解法
背景
见上一篇。 面向对象的链式调用中,掺杂了 一个一部动作, 对于这种工作链, 是非同步执行的链。
LazyMan("Hank").sleep(1).eat("dinner")
同步执行的工作链中, 任何一个动作,即函数调用, 都是同步的, 可理解为普通的函数。
异步的工作链, 前提条件是工作链中,存在至少一个 动作是 异步的。 例如 sleep
Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The
Promiseobject is used for asynchronous computations. APromiserepresents a value which may be available now, or in the future, or never.
A
Promiseis a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future.
A
Promiseis in one of these states:
- pending: initial state, not fulfilled or 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 happens, the associated handlers queued up by a promise's
thenmethod are called.

四大特性:
Promise.all(iterable) --- 我有一个愿望, 等待所有的我指定的愿望 Promise都实现, 我的才能实现。
Promise.race(iterable) --- 我有一个愿望,等待我所指定的愿望中,只要有一个实现, 我的愿望就实现。
Promise.reject(reason) --- 我有一个愿望, 注定不会实现。
Promise.resolve(value) --- 我有一个愿望, 注定要实现。
then特性:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
The
then()method returns aPromise. It takes up to two arguments: callback functions for the success and failure cases of thePromise.
Syntax
p.then(onFulfilled[, onRejected]); p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});Parameters
thenreturns aPromisewhich is determined by the input functions:
- If
onFulfilledoronRejectedthrows an error, or returns aPromisewhich rejects,thenreturns a rejectedPromise.- If
onFulfilledoronRejectedreturns aPromisewhich resolves, or returns any other value,thenreturns a resolvedPromise.
Chaining
The
thenmethod returns aPromisewhich allows for method chaining.You can pass a lambda to
thenand if it returns a promise, an equivalentPromisewill be exposed to the subsequent then in the method chain. The below snippet simulates asynchronous code with thesetTimoutfunction.If
onFulfilledreturns a promise, the return value ofthenwill be resolved/rejected by the promise.
function resolveLater(resolve, reject) {
setTimeout(function () {
resolve(10);
}, 1000);
}
function rejectLater(resolve, reject) {
setTimeout(function () {
reject(20);
}, 1000);
}
var p1 = Promise.resolve("foo");
var p2 = p1.then(function() {
// Return promise here, that will be resolved to 10 after 1 second
return new Promise(resolveLater);
});
p2.then(function(v) {
console.log("resolved", v); // "resolved", 10
}, function(e) {
// not called
console.log("rejected", e);
});
var p3 = p1.then(function() {
// Return promise here, that will be rejected with 20 after 1 second
return new Promise(rejectLater);
});
p3.then(function(v) {
// not called
console.log("resolved", v);
}, function(e) {
console.log("rejected", e); // "rejected", 20
});
解法
结合 then的链使用, 给出方案:
function _LazyMan(name) {
this.promiseGetters = [];
var makePromise = function () {
var promiseObj = new Promise(function(resolve, reject){
console.log("Hi! This is " + name + "!");
resolve();
})
return promiseObj;
}
this.promiseGetters.push(makePromise);
// 在各个Promise的then函数中,将任务序列穿起来
var self = this;
var sequence = Promise.resolve();
// Promise.resolve 等价于
// var sequence = new Promise(function (resolve, reject) {
// resolve();
// })
setTimeout(function(){
for (var i = 0; i < self.promiseGetters.length; i++) {
var nowPromiseGetter = self.promiseGetters[i];
var thenFunc = (function (nowPromiseGetter) {
return function () {
return nowPromiseGetter()
}
})(nowPromiseGetter);
sequence = sequence.then(thenFunc);
};
}, 0); // 在下一个事件循环启动任务
}
_LazyMan.prototype.eat = function(name) {
var makePromise = function () {
var promiseObj = new Promise(function(resolve, reject){
console.log("Eat " + name + "~");
resolve();
})
return promiseObj;
}
this.promiseGetters.push(makePromise);
return this; // 实现链式调用
}
_LazyMan.prototype.sleep = function(time) {
var makePromise = function () {
var promiseObj = new Promise(function(resolve, reject){
setTimeout(function(){
console.log("Wake up after " + time + "s!");
resolve();
}, time * 1000);
})
return promiseObj;
}
this.promiseGetters.push(makePromise);
return this;
}
/* 封装 */
function LazyMan(name){
return new _LazyMan(name);
}
LazyMan("Hank").sleep(1).eat("dinner")
LazyMan的Promise解法的更多相关文章
- 由LazyMan联想到的
LazyMan问题与解法 http://mp.weixin.qq.com/s/drNGvLZddQztcUzSh8OsSw 给出了一道题目,并给出了解法: 题目: 实现一个LazyMan,可以按照以下 ...
- 转评:你造promise就是monad吗
看到一遍好文章,与我的想法如出一辙,先转为敬.首先说说我对Monad和promise的理解: Monad的这种抽象方式是为了简化程序中不确定状态的判断而提出的,能够让程序员从更高的层次顺序描述程序逻辑 ...
- 面试题-lazyMan实现
原文:如何实现一个LazyMan 面试题目 实现一个LazyMan,可以按照以下方式调用: LazyMan('Hank'),输出: Hi, This is Hank! LazyMan('Hank'). ...
- 面试题 LazyMan 的Rxjs实现方式
前言 笔者昨天在做某公司的线上笔试题的时候遇到了最后一道关于如何实现LazyMan的试题,题目如下 实现一个LazyMan,可以按照以下方式调用:LazyMan("Hank")输出 ...
- Promise和async await详解
本文转载自Promise和async await详解 Promise 状态 pending: 初始状态, 非 fulfilled 或 rejected. fulfilled: 成功的操作. rejec ...
- alias导致virtualenv异常的分析和解法
title: alias导致virtualenv异常的分析和解法 toc: true comments: true date: 2016-06-27 23:40:56 tags: [OS X, ZSH ...
- Javascript - Promise学习笔记
最近工作轻松了点,想起了以前总是看到的一个单词promise,于是耐心下来学习了一下. 一:Promise是什么?为什么会有这个东西? 首先说明,Promise是为了解决javascript异步编 ...
- 路由的Resolve机制(需要了解promise)
angular的resovle机制,实际上是应用了promise,在进入特定的路由之前给我们一个做预处理的机会 1.在进入这个路由之前先懒加载对应的 .js $stateProvider .state ...
- Matlab数值计算示例: 牛顿插值法、LU分解法、拉格朗日插值法、牛顿插值法
本文源于一次课题作业,部分自己写的,部分借用了网上的demo 牛顿迭代法(1) x=1:0.01:2; y=x.^3-x.^2+sin(x)-1; plot(x,y,'linewidth',2);gr ...
随机推荐
- ExtJS 中自定义类
首先我们来看一看在Javascript中,是怎样自定义类的: var Person = function (name, age) { this.Name = ""; this.Ag ...
- cmd中编译java
cmd定位到.java文件所在位置: 注意.java文件名应与类名相同. javac xxx.java:编译(生成.class文件): java xxx:运行(执行.class文件): 若类间相互调用 ...
- 试听笔记:javascript入门精通
一.数据类型 1.原始类型:number.string.boolean.null.undefined 2.对象类型:Object (Function.Array.Date...) P.类型隐式转换:' ...
- IIS8的证书设置
首先,打开IIS的网站,找到“服务器证书” 然后根据需要创建证书 创建好后,如果某一个网站(注意是网站,不是应用程序集)需要使用https则, 在右侧“绑定”一项中添加新的https连接,并选择对应的 ...
- ViewPager打造轮播图(Banner)\引导页(Guide)
今年7月时,在Github发布了一个开源的Banner库,虽然Star不多,但还是有少部分人使用. Banner效果: 昨天,有使用此库的同学提出需求,想在引导页的时候用这个库并且最后一页有进入按钮 ...
- python安装第三方类库的方法
1.先到官网 http://pypi.python.org/pypi/setuptools 下载setuptools.exe文件并安装 点击 ez_setup.py进入, 并将内容复制下来, 保存为本 ...
- RStudio技巧01_美化RStudio的帮助页面
R中的package及其函数实在太多,经常遇到不会使用或者忘记如何使用的的package和函数,所以总会查阅帮助文档,在Rstudio中提供了专门的help面板,当遇到不懂的package或者函数时只 ...
- 1.0 多控制器管理(附:Demo)
本文并非最终版本,如有更新或更正会第一时间置顶,联系方式详见文末 如果觉得本文内容过长,请前往本人 “简书” 控制器 : 一个iOS的app很少只由一个控制器组成,除非这个app极其简 ...
- 【Unity3d游戏开发】unity3D OnTriggerEnter和OnCollisionEnter的一点个人心得(转载)
此文为转载,因为最近在做U3D,有一些概念弄得不是很清楚,看到这篇博客讲的不错,就转载过来了,方便自己随时查看. ------------------------------------------- ...
- 【填坑向】spoj COT/bzoj2588 Count on a tree
这题是学主席树的时候就想写的,,, 但是当时没写(懒) 现在来填坑 = =日常调半天lca(考虑以后背板) 主席树还是蛮好写的,但是代码出现重复,不太好,导致调试的时候心里没底(虽然事实证明主席树部分 ...