for (let i = 0; i < 10; i++) {
const promise = new Promise((resolve, reject) => {
const timeout = Math.random() * 1000;
setTimeout(() => {
console.log(i);
}, timeout);
});
// TODO: Chain this promise to the previous one (maybe without having it running?)
}
Run Code Online (Sandbox Code Playgroud)
以上将给出以下随机输出:
6
9
4
8
5
1
7
2
3
0
Run Code Online (Sandbox Code Playgroud)
任务很简单:确保每个promise只在另一个(.then())之后运行.
出于某种原因,我找不到办法.
我尝试了生成函数(yield),尝试了返回promise的简单函数,但在一天结束时它总是归结为同样的问题:循环是同步的.
使用异步我只是使用async.series().
你是如何解决的?
我很难找到使用fetch实现上传进度指示器的文档或示例.
这是迄今为止我发现的唯一参考资料,其中指出:
进度事件是一个高级功能,暂时无法获取.您可以通过查看
Content-Length标头并使用传递流来监视接收的字节来创建自己的标头.这意味着您可以无需另外明确地处理响应
Content-Length.当然,即使在Content-Length那里也可能是谎言.使用流可以根据需要处理这些谎言.
如何编写"传输流来监控字节"发送?如果它产生任何差异,我正在尝试这样做以支持从浏览器到Cloudinary的图像上传.
注意:我对Cloudinary JS库不感兴趣,因为它依赖于jQuery而我的应用程序没有.我只对使用原生javascript和Github的polyfill 执行此操作所需的流处理感兴趣.fetch
我有一些代码在一个列表中进行迭代,该列表从数据库中查询并为该列表中的每个元素发出HTTP请求.该列表有时可能是一个相当大的数字(成千上万),我想确保我没有遇到数千个并发HTTP请求的Web服务器.
此代码的缩写版本目前看起来像这样......
function getCounts() {
return users.map(user => {
return new Promise(resolve => {
remoteServer.getCount(user) // makes an HTTP request
.then(() => {
/* snip */
resolve();
});
});
});
}
Promise.all(getCounts()).then(() => { /* snip */});
Run Code Online (Sandbox Code Playgroud)
此代码在Node 4.3.2上运行.重申Promise.all一下,可以进行管理,以便在任何给定时间只有一定数量的Promise正在进行中?
我正在使用该async.eachLimit功能一次控制最大操作数.
const { eachLimit } = require("async");
function myFunction() {
return new Promise(async (resolve, reject) => {
eachLimit((await getAsyncArray), 500, (item, callback) => {
// do other things that use native promises.
}, (error) => {
if (error) return reject(error);
// resolve here passing the next value.
});
});
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我无法将该myFunction函数声明为异步,因为我无法访问eachLimit函数的第二个回调内的值.
我正在尝试使用Angular2路由器防护来限制对我的应用程序中某些页面的访问.我正在使用Firebase身份验证.为了检查用户是否使用Firebase登录,我必须使用回调调用.subscribe()该FirebaseAuth对象.这是守卫的代码:
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFireAuth } from "angularfire2/angularfire2";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AngularFireAuth, private router: Router) {}
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>|boolean {
this.auth.subscribe((auth) => {
if (auth) {
console.log('authenticated');
return true;
}
console.log('not authenticated');
this.router.navigateByUrl('/login');
return false;
});
}
}
Run Code Online (Sandbox Code Playgroud)
当导航到对其具有防护的页面时authenticated,或者not authenticated打印到控制台(在等待来自firebase的响应的一些延迟之后).但是,导航永远不会完成.此外,如果我没有登录,我将被重定向到该/login路线.因此,我遇到的问题是return true不向用户显示请求的页面.我假设这是因为我正在使用回调,但我无法弄清楚如何做到这一点.有什么想法吗?
在这个答案中,一个承诺链是递归建立的.
稍微简化,我们有:
function foo() {
function doo() {
// always return a promise
if (/* more to do */) {
return doSomethingAsync().then(doo);
} else {
return Promise.resolve();
}
}
return doo(); // returns a promise
}
Run Code Online (Sandbox Code Playgroud)
据推测,这会产生一个调用堆栈和一个承诺链 - 即"深"和"宽".
我预计内存峰值会大于执行递归或单独建立一个promise链.
编辑
代码为#1.继续重试,直到诺言解决(语言的任何改进社区等?)
Promise.retry = function(fn, times, delay) {
return new Promise(function(resolve, reject){
var error;
var attempt = function() {
if (times == 0) {
reject(error);
} else {
fn().then(resolve)
.catch(function(e){
times--;
error = e;
setTimeout(function(){attempt()}, delay);
});
}
};
attempt();
});
};
Run Code Online (Sandbox Code Playgroud)
使用
work.getStatus()
.then(function(result){ //retry, some glitch in the system
return Promise.retry(work.unpublish.bind(work, result), 10, 2000);
})
.then(function(){console.log('done')})
.catch(console.error);
Run Code Online (Sandbox Code Playgroud)
#2的代码继续重试,直到条件then以可重用的方式满足结果(条件是变化的).
work.publish()
.then(function(result){
return new Promise(function(resolve, reject){
var intervalId = setInterval(function(){
work.requestStatus(result).then(function(result2){
switch(result2.status) { …Run Code Online (Sandbox Code Playgroud) 我正在处理需要某个函数同步的NodeJs框架,但我需要检索一个只能异步访问的值.在一个完美的世界里,我能够回报一个承诺,但我不能.
作为一个快速而肮脏的解决方案,我创建了以下方法:
exports.synchronizePromise = function(promise) {
var value;
promise.then(function(promiseValue) {
value = promiseValue;
});
while (!value) {} // Wait for promise to resolve
console.log("DONE: " + value); // Never reached
return value;
};
Run Code Online (Sandbox Code Playgroud)
但是我收到了一个错误.有没有办法完成我需要的东西?
这是将jQuery转换Deferred为的正确方法Promise吗?
var p = Promise.resolve($.getJSON('api/values', null));
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以做到这一点?
有什么限制?我已经读过某个地方,jQuery延迟不支持异常,所以我假设从延迟创建的承诺都不会.它是否正确?
我试图了解JavaScript中的承诺(特别是AngularJS).
我在服务中有一个函数,让我们调用它fooService,检查我们是否加载了一些数据.如果有,我只想让它返回,如果我们没有,我们需要加载数据并返回一个承诺:
this.update = function(data_loaded) {
if (data_loaded) return; // We've loaded the data, no need to update
var promise = Restangular.all('someBase').customGet('foo/bar').then(function(data) {
// Do something with the data here
}
return promise;
}
Run Code Online (Sandbox Code Playgroud)
我有另一个函数然后调用这样的update函数fooService:
fooService.update(data_loaded).then(function() {
// Do something here when update is finished
})
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我们不需要在update函数中加载数据,则不返回promise,因此.then()不会在我的其他函数中调用.该方法应该在这里 - 基本上我想立即从update()函数返回一个已解决的承诺,如果我们不需要从Restangular调用中获取数据?
javascript ×9
node.js ×4
promise ×4
es6-promise ×2
angular ×1
angularjs ×1
async-await ×1
asynchronous ×1
fetch-api ×1
html5 ×1
jquery ×1
q ×1
recursion ×1
restangular ×1
typescript ×1