// index.js
/*
1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
2. Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
pending -> fulfilled
pending -> rejected
一旦状态确定就不可更改
3. resolve和reject函数是用来更改状态的
resolve: fulfilled
reject: rejected
4. then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
6. 同一个promise对象下面的then方法是可以被调用多次的
7. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
*/
const MyPromise = require('./myPromise');
function p1 () {
return new MyPromise(function (resolve, reject) {
setTimeout(function () {
resolve('p1')
}, 2000)
})
}
function p2 () {
return new MyPromise(function (resolve, reject) {
reject('失败')
// resolve('成功');
})
}
p2()
.then(value => console.log(value))
.catch(reason => console.log(reason))
// myPromise.js
const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败
class MyPromise {
constructor (executor) {
try {
executor(this.resolve, this.reject)
} catch (e) {
this.reject(e);
}
}
// promsie 状态
status = PENDING;
// 成功之后的值
value = undefined;
// 失败后的原因
reason = undefined;
// 成功回调
successCallback = [];
// 失败回调
failCallback = [];
resolve = value => {
// 如果状态不是等待 阻止程序向下执行
if (this.status !== PENDING) return;
// 将状态更改为成功
this.status = FULFILLED;
// 保存成功之后的值
this.value = value;
// 判断成功回调是否存在 如果存在 调用
// this.successCallback && this.successCallback(this.value);
while(this.successCallback.length) this.successCallback.shift()()
}
reject = reason => {
// 如果状态不是等待 阻止程序向下执行
if (this.status !== PENDING) return;
// 将状态更改为失败
this.status = REJECTED;
// 保存失败后的原因
this.reason = reason;
// 判断失败回调是否存在 如果存在 调用
// this.failCallback && this.failCallback(this.reason);
while(this.failCallback.length) this.failCallback.shift()()
}
then (successCallback, failCallback) {
// 参数可选
successCallback = successCallback ? successCallback : value => value;
// 参数可选
failCallback = failCallback ? failCallback: reason => { throw reason };
let promsie2 = new MyPromise((resolve, reject) => {
// 判断状态
if (this.status === FULFILLED) {
setTimeout(() => {
try {
let x = successCallback(this.value);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
}else if (this.status === REJECTED) {
setTimeout(() => {
try {
let x = failCallback(this.reason);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
} else {
// 等待
// 将成功回调和失败回调存储起来
this.successCallback.push(() => {
setTimeout(() => {
try {
let x = successCallback(this.value);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
});
this.failCallback.push(() => {
setTimeout(() => {
try {
let x = failCallback(this.reason);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
});
}
});
return promsie2;
}
finally (callback) {
return this.then(value => {
return MyPromise.resolve(callback()).then(() => value);
}, reason => {
return MyPromise.resolve(callback()).then(() => { throw reason })
})
}
catch (failCallback) {
return this.then(undefined, failCallback)
}
static all (array) {
let result = [];
let index = 0;
return new MyPromise((resolve, reject) => {
function addData (key, value) {
result[key] = value;
index++;
if (index === array.length) {
resolve(result);
}
}
for (let i = 0; i < array.length; i++) {
let current = array[i];
if (current instanceof MyPromise) {
// promise 对象
current.then(value => addData(i, value), reason => reject(reason))
}else {
// 普通值
addData(i, array[i]);
}
}
})
}
static resolve (value) {
if (value instanceof MyPromise) return value;
return new MyPromise(resolve => resolve(value));
}
}
function resolvePromise (promsie2, x, resolve, reject) {
if (promsie2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
if (x instanceof MyPromise) {
// promise 对象
// x.then(value => resolve(value), reason => reject(reason));
x.then(resolve, reject);
} else {
// 普通值
resolve(x);
}
}
module.exports = MyPromise;
在执行所有promise后,我正在尝试进行一些计算。但是proc从不调用:cbr_promise=Concurrent::Promise.execute{CbrRatesService.call}bitfinex_promise=Concurrent::Promise.execute{BitfinexService.call}proc=Proc.newdoputs10endConcurrent::Promise.all?([cbr_promise,bitfinex_promise]).then{proc}使用concurrent-ruby制作gem。例如,我是否应该创建一个每100毫秒
我有一个这样的字典:{go:['went','run'],love:['passion','like']}键的值是它的同义词。'getSynonymWords(word)'是一个异步函数,它返回一个promise,其中它的值是与传递的参数对应的同义词列表。我怎样才能像这样循环遍历对象以递归地获取另一个对象:{went:[],run:[],passion:[],like:[]}这是我的一段代码:functiongetRelatedWords(dict){returnnewPromise(function(resolve){varnewDict={};for(varkeyindict){i
我正在尝试使用$q.all等待所有promise都已解决,但它是在第一个promise完成后调用的!我做错了什么?functionsendAudits(audits){varpromises=[];$scope.sendAudits={progress:0};angular.forEach(audits,function(audit,idAudit){promises.push(saveAudit(audit));});$q.all(promises).then(function(data){console.log(data);},function(errors){console.lo
所以我试图将我的代码转移到“Promise世界”,并且在许多地方当我不得不使用异步功能“循环”时-我只是以这种方式使用递归functiondoRecursion(idx,callback){if(idx现在我正在尝试改变Promise世界,但我很困varPromise=require('bluebird')functiondoRecursion(idx){returnnewPromise(function(resolve){if(idx谢谢。 最佳答案 我会选择Promise.all方法。它所做的是等待数组中的所有promise都已
我正在使用ES6promises,这个函数的想法是遍历一组链接,并为每个链接查找一个图像并在找到图像后停止。在我编写的函数的这种情况下,最快的promise已解析,其他promise继续执行,因此我想要的是在第一个promise解析后立即停止执行剩余的promise。scrapImage(links){letpromises=links.map((l)=>getImageUrlAsync(l));returnPromise.race(promises);} 最佳答案 promise不会“执行”。它们是返回值,而不是函数。promis
背景我通常基于async.js编写node.js脚本来控制工作流程。有时我发现基于async.js,代码似乎仍然是一个“hell”。使用多个嵌套,代码不可读且难以维护。我在这里进行了一些搜索,发现了一些有用的资源——但其中大部分都是一般概念。所以我要问一个问题。如有任何反馈,我们将不胜感激。我的常用代码varrequest=require('request');varasync=require('async');vararray=[1,2,3,4,5,6];varurl='http://www.google.com';async.mapLimit(array,3,function(nu
我已经开始学习javascriptpromises。但我就是无法理解promise的概念。最让我困扰的是谁将Resolver和Reject函数传递给promise构造函数?请看这个Promise的例子:functiongetImage(url){returnnewPromise(function(resolve,reject){varimg=newImage()img.onload=function(){resolve(url)}img.onerror=function(){reject(url)}img.src=url})}现在谁确实传递了resolve和reject方法,正如我对j
我正在尝试使用RxJSv5beta为表单实现“保存类型”功能.当用户在文本字段中输入时,数据应该被发送到后端。我正在创建一个Rx.Subject来为新用户输入触发新事件(next())并将其与HTTP请求一起发布。我以这个问题为起点:RxJSwaituntilpromiseresolved但是,使用这篇文章中的解决方案,同时向后端发送请求。我的目标是只发送一个请求并推迟后续请求,直到正在运行的请求完成。完成请求后,应发出最后一个未决事件(就像debounceTime中的情况一样)以下代码段中的示例函数使用链接的SO问题中的方法。这将发送对所有输入值的请求。workaround函数使用存
我正在学习javascript中的类和继承。我认为以下是扩展现有对象的相当标准的方法,因为我从MDNdocsonObject.create中获得了样式。我期待看到“好的”,然后是“耶!你好'在控制台中,但我却出现了这个错误:UncaughtTypeError:#isnotapromiseatnewMyPromise(:5:17)at:19:6看起来Promise构造函数正在抛出异常,因为它可以告诉我我给它初始化的对象不是一个简单的Promise。我希望Promise构造函数将我的对象初始化为Promise对象,这样我就可以扩展该类。他们为什么不编写Promise构造函数来处理这种通用模
我正在开发Spotify应用程序。我能够登录并获取我的token。我的问题是我无法访问方法外的变量。在这种情况下"getCurrentUser"这是我的方法:functiongetUser(){if($localStorage.token==undefined){throwalert("Notloggedin");}else{Spotify.getCurrentUser().then(function(data){varnames=JSON.stringify(data.data.display_name);console.log(names)})}};如您所见,我在console.l