我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
我想澄清这一点,因为文件不太清楚;
Q1:是Promise.all(iterable)处理所有的承诺顺序或并行?或者,更具体地说,它是否相当于运行链式承诺
p1.then(p2).then(p3).then(p4).then(p5)....
Run Code Online (Sandbox Code Playgroud)
或者是一些其他类型的算法的所有p1,p2,p3,p4,p5,等是被称为在同一时间(并行)和结果尽快返回所有的决心(或一个拒绝)?
Q2:如果Promise.all并行运行,是否有一种方便的方式来运行可迭代的顺序?
注意:我不想使用Q或Bluebird,而是使用所有原生ES6规范.
如何正确构造一个循环以确保后续的promise调用和链式logger.log(res)通过迭代同步运行?(蓝鸟)
db.getUser(email).then(function(res) { logger.log(res); }); // this is a promise
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法(来自http://blog.victorquinn.com/javascript-promise-while-loop的方法)
var Promise = require('bluebird');
var promiseWhile = function(condition, action) {
var resolver = Promise.defer();
var loop = function() {
if (!condition()) return resolver.resolve();
return Promise.cast(action())
.then(loop)
.catch(resolver.reject);
};
process.nextTick(loop);
return resolver.promise;
});
var count = 0;
promiseWhile(function() {
return count < 10;
}, function() {
return new Promise(function(resolve, reject) {
db.getUser(email)
.then(function(res) {
logger.log(res);
count++;
resolve();
});
});
}).then(function() {
console.log('all done');
}); …Run Code Online (Sandbox Code Playgroud) 在promise库Q中,您可以执行以下操作来按顺序链接promise:
var items = ['one', 'two', 'three'];
var chain = Q();
items.forEach(function (el) {
chain = chain.then(foo(el));
});
return chain;
Run Code Online (Sandbox Code Playgroud)
但是,以下内容不适用于$ q:
var items = ['one', 'two', 'three'];
var chain = $q();
items.forEach(function (el) {
chain = chain.then(foo(el));
});
return chain;
Run Code Online (Sandbox Code Playgroud) 如何Promise使用Q库创建JavaScript 的递归链?以下代码无法在Chrome中完成:
<html>
<script src="q.js" type="text/javascript"></script>
<script type="text/javascript">
//Don't keep track of a promises stack for debugging
//Reduces memory usage when recursing promises
Q.longStackJumpLimit = 0;
function do_stuff(count) {
if (count==1000000) {
return;
}
if (count%10000 == 0){
console.log( count );
}
return Q.delay(1).then(function() {
return do_stuff(count+1);
});
}
do_stuff(0)
.then(function() {
console.log("Done");
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud) 我理解Promise存在于以下三种状态之一:Promise可以是待处理(未解析),履行(成功解决)或拒绝(解决失败).
阅读A + Promise Spec和MDN的文档,我很困惑他们都承认已完成和被拒绝的状态,但在Promise构造函数的定义中,他们指定了两个回调:resolve和reject.我们似乎可以互换地使用这两个术语; 他们不是.
并不意味着成功:
re·solve /r??zälv/ verb
1. settle or find a solution to (a problem, dispute, or contentious matter).
Run Code Online (Sandbox Code Playgroud)
是否意味着成功:
ful·fill /fo?ol?fil/ verb
1. bring to completion or reality; achieve or realize (something desired, promised, or predicted).
2. carry out (a task, duty, or role) as required, pledged, or expected.
Run Code Online (Sandbox Code Playgroud)
当我们真正实现承诺时,为什么我们在这里使用决心?有没有在其中的价值,我们通过一个实例解决可能会导致无极是拒绝 …
我正在尝试为上述问题编写代码.我试着寻找解决方案.这就是我现在拥有的.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var drawColorLine = function(start, end, color) {
var deltaX, deltaY, i = 0,
currLength = 0,
isHor, isVert;
deltaX = end[0] - start[0];
deltaY = end[1] - start[1];
context.strokeStyle = color;
isHor = deltaX === 0 ? 0 : 1;
isVert = deltaY === 0 ? 0 : 1;
function draw() {
context.beginPath();
context.moveTo(start[0] + currLength * isHor, start[1] + currLength * isVert);
currLength = currLength + 0.5 * i;
context.lineTo(start[0] …Run Code Online (Sandbox Code Playgroud)我开发了一个客户端库,它公开了一个名为的方法iterator().此方法返回使用require('promise')库创建的Promise实例,该实例使用迭代器对象完成.
该对象包含一个调用的方法next(),该方法返回一个Promise,它使用如下复杂对象完成:{done: [true|false], key: _, value: _}
虽然iterator()可能预先获取一些元素,next()但是如果它导致远程调用,则需要返回Promise.
现在,假设用户想要迭代所有元素,直到返回的Promise返回next()包含的对象done: true.
我已经设法使用以下递归方法实现了这一点(我最初在这个答案中找到了这个解决方案):
var iterate = client.iterator();
iterateTeams.then(function(it) {
function loop(promise, fn) {
// Simple recursive loop over iterator's next() call
return promise.then(fn).then(function (entry) {
return !entry.done ? loop(it.next(), fn) : entry;
});
}
return loop(it.next(), function (entry) {
console.log('entry is: ' + entry);
return entry;
});
});
Run Code Online (Sandbox Code Playgroud)
问题是,是否可以使用require('promise')库来构建非递归解决方案?我对非递归方法感兴趣的原因是,如果要迭代的条目数太大,就要避免爆炸.
干杯,高尔德
我正在玩承诺,我遇到异步递归承诺的问题.
场景是运动员开始跑100米,我需要定期检查他们是否已经完成,一旦完成,打印他们的时间.
编辑澄清:
在现实世界中,运动员在服务器上运行.startRunning涉及对服务器进行ajax调用.checkIsFinished还涉及对服务器进行ajax调用.下面的代码试图模仿它.代码中的时间和距离是硬编码的,以尽量使事情变得简单.道歉不清楚.
结束编辑
我希望能够写下以下内容
startRunning()
.then(checkIsFinished)
.then(printTime)
.catch(handleError)
Run Code Online (Sandbox Code Playgroud)
哪里
var intervalID;
var startRunning = function () {
var athlete = {
timeTaken: 0,
distanceTravelled: 0
};
var updateAthlete = function () {
athlete.distanceTravelled += 25;
athlete.timeTaken += 2.5;
console.log("updated athlete", athlete)
}
intervalID = setInterval(updateAthlete, 2500);
return new Promise(function (resolve, reject) {
setTimeout(resolve.bind(null, athlete), 2000);
})
};
var checkIsFinished = function (athlete) {
return new Promise(function (resolve, reject) {
if (athlete.distanceTravelled >= 100) …Run Code Online (Sandbox Code Playgroud) 我一直在学习使用蓝鸟两周的承诺.我对他们大多了解,但我去解决一些相关的问题,似乎我的知识已经崩溃了.我正在尝试这个简单的代码:
var someGlobal = true;
whilePromsie(function() {
return someGlobal;
}, function(result) { // possibly even use return value of 1st parm?
// keep running this promise code
return new Promise(....).then(....);
});
Run Code Online (Sandbox Code Playgroud)
作为一个具体的例子:
// This is some very contrived functionality, but let's pretend this is
// doing something external: ajax call, db call, filesystem call, etc.
// Simply return a number between 0-999 after a 0-999 millisecond
// fake delay.
function getNextItem() {
return new Promise.delay(Math.random()*1000).then(function() {
Promise.cast(Math.floor(Math.random() * 1000));
}); …Run Code Online (Sandbox Code Playgroud) javascript ×9
promise ×9
bluebird ×3
es6-promise ×3
q ×3
node.js ×2
recursion ×2
angularjs ×1
asynchronous ×1
canvas ×1
chaining ×1
memory-leaks ×1
sequential ×1