어떤 방법으로 이 성어는 귈이예요 함께 루프가 약속 같은 일이 될 것 "이라고 말했다. 그래서:
뭔가 만약 이 조건이 여전히 스탠드 do it again 반복하십시오 재동기화할 something else.
dosomething.then(possilblydomoresomethings).then(finish)
var q = require('q');
var index = 1;
var useless = function(){
var currentIndex = index;
console.log(currentIndex)
var deferred = q.defer();
setTimeout(function(){
if(currentIndex > 10)
deferred.resolve(false);
else deferred.resolve(true);
},500);
return deferred.promise;
}
var control = function(cont){
var deferred = q.defer();
if(cont){
index = index + 1;
useless().then(control).then(function(){
deferred.resolve();
});
}
else deferred.resolve();
return deferred.promise;
}
var chain = useless().then(control).then(function(){console.log('done')});
출력: 1 2 3 4 5 6 7 8 9 10 11 수행되
S # 39 here& 재사용 가능한 함수, 제가 생각하는 확실합니다.
var Q = require("q");
// `condition` is a function that returns a boolean
// `body` is a function that returns a promise
// returns a promise for the completion of the loop
function promiseWhile(condition, body) {
var done = Q.defer();
function loop() {
// When the result of calling `condition` is no longer true, we are
// done.
if (!condition()) return done.resolve();
// Use `when`, in case `body` does not return a promise.
// When it completes loop again otherwise, if it fails, reject the
// done promise
Q.when(body(), loop, done.reject);
}
// Start running the loop in the next tick so that this function is
// completely async. It would be unexpected if `body` was called
// synchronously the first time.
Q.nextTick(loop);
// The promise
return done.promise;
}
// Usage
var index = 1;
promiseWhile(function () { return index <= 11; }, function () {
console.log(index);
index++;
return Q.delay(500); // arbitrary async
}).then(function () {
console.log("done");
}).done();
<! - 언어: > es6 -;
const doSomething = value =>
new Promise(resolve =>
setTimeout(() => resolve(value >= 5 ? 'ok': 'no'), 1000))
const loop = value =>
doSomething(value).then(result => {
console.log(value)
if (result === 'ok') {
console.log('yay')
} else {
return loop(value + 1)
}
})
loop(1).then(() => console.log('all done!'))
[See it in action 에 이스빈] (https://jsbin.com/wirumixojo/edit? js, 콘솔)
약속이 사용한 경우, 또는 '정의' 와 '다음' 거부됩니다 해결하는 것과 잘 사용하는 대신 만약 조.
그냥 '반복' 을 했을 경우, 또는 pop 배열입니다 됩니다 공약을 변경하십시오 shift+ctrl 다음 각 1 시간.
편집: # 39 의 버전 ',' 비동기 / 기다리고 있기 때문에 사용하는 here& it& # 39 의 2018년:
const loop = async value => {
let result = null
while (result != 'ok') {
console.log(value)
result = await doSomething(value)
value = value + 1
}
console.log('yay')
}
[See it in action 에 고데펜] (https://codepen.io/anon/pen/jzpZMa? 편집자 = 0011)
정상적인 볼 수 있듯이, while 루프를 사용하며 않고 반복.
D 개체를 사용하여 i& # 39 랩 값입니다. 루프 알 수 있도록 이쪽요 있을 수 있습니다 '속성' 수행됨 you& # 39, re done.
// fn should return an object like
// {
// done: false,
// value: foo
// }
function loop(promise, fn) {
return promise.then(fn).then(function (wrapper) {
return !wrapper.done ? loop(Q(wrapper.value), fn) : wrapper.value;
});
}
loop(Q.resolve(1), function (i) {
console.log(i);
return {
done: i > 10,
value: i++
};
}).done(function () {
console.log('done');
});
이 때문에 특별히 하라님의 q, q t # 39 didn& 캐비닛용입니다 블루버드 않고 있습니다. 저자는 이 성어는 약속하나요 생성 반환하는 함수를 사용하는 것보다 더 많은 언급을 블루버드 apiu doc 약간만이라도 우회된.
var Promise = require('bluebird');
var i = 0;
var counter = Promise.method(function(){
return i++;
})
function getAll(max, results){
var results = results || [];
return counter().then(function(result){
results.push(result);
return (result < max) ? getAll(max, results) : results
})
}
getAll(10).then(function(data){
console.log(data);
})
이제 이 패턴을 사용하여 보다 쉽게 불렀으매 q 흐름. 예를 들어, 위의 문제:
var q = require('q');
require('q-flow');
var index = 1;
q.until(function() {
return q.delay(500).then(function() {
console.log(index++);
return index > 10;
});
}).done(function() {
return console.log('done');
});
여기에 대한 확장을 위해 'a' 의 비헤이비어를 한다 '는 "에 대한 루프지 약속하나요 프로토타입 이 제품은 공약 또는 즉시 값을 루프 초기화하지, 조건, 본문, 증분식 단면에는. 또한, 그리고 메모리 누수가 예외에 대한 전폭적인 지원을 가지고 있지 않다. 예를 들면 아래와 on how to use it.
var Promise = require('promise');
// Promise.loop([properties: object]): Promise()
//
// Execute a loop based on promises. Object 'properties' is an optional
// argument with the following fields:
//
// initialization: function(): Promise() | any, optional
//
// Function executed as part of the initialization of the loop. If
// it returns a promise, the loop will not begin to execute until
// it is resolved.
//
// Any exception occurring in this function will finish the loop
// with a rejected promise. Similarly, if this function returns a
// promise, and this promise is reject, the loop finishes right
// away with a rejected promise.
//
// condition: function(): Promise(result: bool) | bool, optional
//
// Condition evaluated in the beginning of each iteration of the
// loop. The function should return a boolean value, or a promise
// object that resolves with a boolean data value.
//
// Any exception occurring during the evaluation of the condition
// will finish the loop with a rejected promise. Similarly, it this
// function returns a promise, and this promise is rejected, the
// loop finishes right away with a rejected promise.
//
// If no condition function is provided, an infinite loop is
// executed.
//
// body: function(): Promise() | any, optional
//
// Function acting as the body of the loop. If it returns a
// promise, the loop will not proceed until this promise is
// resolved.
//
// Any exception occurring in this function will finish the loop
// with a rejected promise. Similarly, if this function returns a
// promise, and this promise is reject, the loop finishes right
// away with a rejected promise.
//
// increment: function(): Promise() | any, optional
//
// Function executed at the end of each iteration of the loop. If
// it returns a promise, the condition of the loop will not be
// evaluated again until this promise is resolved.
//
// Any exception occurring in this function will finish the loop
// with a rejected promise. Similarly, if this function returns a
// promise, and this promise is reject, the loop finishes right
// away with a rejected promise.
//
Promise.loop = function(properties)
{
// Default values
properties = properties || {};
properties.initialization = properties.initialization || function() { };
properties.condition = properties.condition || function() { return true; };
properties.body = properties.body || function() { };
properties.increment = properties.increment || function() { };
// Start
return new Promise(function(resolve, reject)
{
var runInitialization = function()
{
Promise.resolve().then(function()
{
return properties.initialization();
})
.then(function()
{
process.nextTick(runCondition);
})
.catch(function(error)
{
reject(error);
});
}
var runCondition = function()
{
Promise.resolve().then(function()
{
return properties.condition();
})
.then(function(result)
{
if (result)
process.nextTick(runBody);
else
resolve();
})
.catch(function(error)
{
reject(error);
});
}
var runBody = function()
{
Promise.resolve().then(function()
{
return properties.body();
})
.then(function()
{
process.nextTick(runIncrement);
})
.catch(function(error)
{
reject(error);
});
}
var runIncrement = function()
{
Promise.resolve().then(function()
{
return properties.increment();
})
.then(function()
{
process.nextTick(runCondition);
})
.catch(function(error)
{
reject(error);
});
}
// Start running initialization
process.nextTick(runInitialization);
});
}
// Promise.delay(time: double): Promise()
//
// Returns a promise that resolves after the given delay in seconds.
//
Promise.delay = function(time)
{
return new Promise(function(resolve)
{
setTimeout(resolve, time * 1000);
});
}
// Example
var i;
Promise.loop({
initialization: function()
{
i = 2;
},
condition: function()
{
return i < 6;
},
body: function()
{
// Print "i"
console.log(i);
// Exception when 5 is reached
if (i == 5)
throw Error('Value of "i" reached 5');
// Wait 1 second
return Promise.delay(1);
},
increment: function()
{
i++;
}
})
.then(function()
{
console.log('LOOP FINISHED');
})
.catch(function(error)
{
console.log('EXPECTED ERROR:', error.message);
});
나는 이제 이를 통해:
function each(arr, work) {
function loop(arr, i) {
return new Promise(function(resolve, reject) {
if (i >= arr.length) {resolve();}
else try {
Promise.resolve(work(arr[i], i)).then(function() {
resolve(loop(arr, i+1))
}).catch(reject);
} catch(e) {reject(e);}
});
}
return loop(arr, 0);
}
이 기능을 사용할 수 있는 '도착' 와 '작업' 와 'a' 되돌려줍니다 어레이에서는 약속하나요 '. Gets 함수를 배열의 각 요소에 대해 한 번 불렀으매 제공된 현재 받고 있는 지 요소 및 it& # 39 의 인덱스화할 어레이입니다. 동기화됨 약속이 있을 수 있는 경우 또는 async 반품해야 합니다.
이렇게 사용할 수 있습니다.
var items = ['Hello', 'cool', 'world'];
each(items, function(item, idx) {
// this could simply be sync, but can also be async
// in which case it must return a Promise
return new Promise(function(resolve){
// use setTimeout to make this async
setTimeout(function(){
console.info(item, idx);
resolve();
}, 1000);
});
})
.then(function(){
console.info('DONE');
})
.catch(function(error){
console.error('Failed', error);
})
각 항목에는 어레이입니다 처리할 수 있는 선반가공. 한 번 () 에게 '코드' 가 모두 처리됩니까 .즉, 일부 오류가 발생했을 경우, 또는 실행하십시오 스카치 () 에게 '코드'. '내' 투사 '는' 기능을 사용할 수 있습니다 '오류' 또는 '거부' (동기식에서의 경우 기능) 이 '약속' () 의 경우, 비동기 함수) 를 루프지 중단합니다.
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 참 - >.
function each(arr, work) {
function loop(arr, i) {
return new Promise(function(resolve, reject) {
if (i >= arr.length) {resolve();}
else try {
Promise.resolve(work(arr[i], i)).then(function() {
resolve(loop(arr, i+1))
}).catch(reject);
} catch(e) {reject(e);}
});
}
return loop(arr, 0);
}
var items = ['Hello', 'cool', 'world'];
each(items, function(item, idx) {
// this could simply be sync, but can also be async
// in which case it must return a Promise
return new Promise(function(resolve){
// use setTimeout to make this async
setTimeout(function(){
console.info(item, idx);
resolve();
}, 1000);
});
})
.then(function(){
console.info('DONE');
})
.catch(function(error){
console.error('Failed', error);
})
끝 - < 스니핏 >;!
var Q = require('q')
var vetor = ['a','b','c']
function imprimeValor(elements,initValue,defer){
console.log( elements[initValue++] )
defer.resolve(initValue)
return defer.promise
}
function Qloop(initValue, elements,defer){
Q.when( imprimeValor(elements, initValue, Q.defer()), function(initValue){
if(initValue===elements.length){
defer.resolve()
}else{
defer.resolve( Qloop(initValue,elements, Q.defer()) )
}
}, function(err){
defer.reject(err)
})
return defer.promise
}
Qloop(0, vetor,Q.defer())
여기에 대답을 얻기 위해 많이 노력하고 있고 실질적인 너희는너희가 것만은 아닙니다. 그러나 이 노력해야 합니다. 이는 작업공간에서 구현됩니까 aws 람다 함수, 연파란색은 node. js 10 것입니다 보살피되 함수은 시간초과했습니다. 제대로 된 메모리 용량을 사용할 수도 있습니다.
exports.handler = async (event) => {
let res = null;
while (true) {
try{
res = await dopromise();
}catch(err){
res = err;
}
console.log(res);
}//infinite will time out
};
function dopromise(){
return new Promise((resolve, reject) => {
//do some logic
//if error reject
//reject('failed');
resolve('success');
});
}
하지만 다른 실행 및 람다 (λ) 에 비해 5 마더보드당 테스트되었습니다 과태료를 명시된 대로 좋은 먼저 할 일이 아니다.
내가 ES6 사용하여 약속하나요 한국증권선물거래소법을. 정보기술 (it) 체인 및 되돌려줍니다 이런 약속은 약속. # 39 의 it& 귈이예요 루프 않지만, 엄밀히 말해 공약을 동시에 반복할 방법을 보여줍니다.
<! - begin 스니핏: js 숨기십시오: > 거짓값 -;
function chain_promises(list, fun) {
return list.reduce(
function (promise, element) {
return promise.then(function () {
// I only needed to kick off some side-effects. If you need to get
// a list back, you would append to it here. Or maybe use
// Array.map instead of Array.reduce.
fun(element);
});
},
// An initial promise just starts things off.
Promise.resolve(true)
);
}
// To test it...
function test_function (element) {
return new Promise(function (pass, _fail) {
console.log('Processing ' + element);
pass(true);
});
}
chain_promises([1, 2, 3, 4, 5], test_function).then(function () {
console.log('Done.');
});
끝 - < 스니핏 >;!
[# 39 의 Here& 내 해야했다.] [1]
그냥 오늘은 throw in the ring my hat 생각해봤죠 사용하여 ES6 공약.
function until_success(executor){
var before_retry = undefined;
var outer_executor = function(succeed, reject){
var rejection_handler = function(err){
if(before_retry){
try {
var pre_retry_result = before_retry(err);
if(pre_retry_result)
return succeed(pre_retry_result);
} catch (pre_retry_error){
return reject(pre_retry_error);
}
}
return new Promise(executor).then(succeed, rejection_handler);
}
return new Promise(executor).then(succeed, rejection_handler);
}
var outer_promise = new Promise(outer_executor);
outer_promise.before_retry = function(func){
before_retry = func;
return outer_promise;
}
return outer_promise;
}
이 인수는 [같은] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 를 통과한 '집행관' 로 불릴 때까지 반복해서 할 뿐, '성공' 약속하나요 구성자를 트리거합니다 콜백하는. 사용자 정의 오류 처리 기능을 이용하면 before_retry '이' 의 실패로. 이 값을 반환하는 경우, 일종의 성공 및 " loop" 트루시 한 것으로 간주된다. 그 결과, 연파란색은 트루시 끝을 맺는다. '또는' 기능이 없는 경우, 그 값을 돌려준다 파우시 before_retry 등록되어 있는 다른 이터레이션에 루프는. 세 번째 옵션은 던지는 '기능이 있는' before_retry 오류가 있다. 이 경우, 다음 " loop". 해당 오류를 반군지역 오류로, 끝을 맺는다.
var counter = 0;
function task(succ, reject){
setTimeout(function(){
if(++counter < 5)
reject(counter + " is too small!!");
else
succ(counter + " is just right");
}, 500); // simulated async task
}
until_success(task)
.before_retry(function(err){
console.log("failed attempt: " + err);
// Option 0: return falsey value and move on to next attempt
// return
// Option 1: uncomment to get early success..
//if(err === "3 is too small!!")
// return "3 is sort of ok";
// Option 2: uncomment to get complete failure..
//if(err === "3 is too small!!")
// throw "3rd time, very unlucky";
}).then(function(val){
console.log("finally, success: " + val);
}).catch(function(err){
console.log("it didn't end well: " + err);
})
출력입니다 옵션에 대해 0:
failed attempt: 1 is too small!!
failed attempt: 2 is too small!!
failed attempt: 3 is too small!!
failed attempt: 4 is too small!!
finally, success: 5 is just right
출력하는 옵션 1:
failed attempt: 1 is too small!!
failed attempt: 2 is too small!!
failed attempt: 3 is too small!!
finally, success: 3 is sort of ok
출력하는 옵션 2:
failed attempt: 1 is too small!!
failed attempt: 2 is too small!!
failed attempt: 3 is too small!!
it didn't end well: 3rd time, very unlucky
내가 쓴 《 모듈에서는 체인된 루프 비동기적입니다 작업을 할 데 도움이 되는 것은 약속을 기반으로 제공하는 그들위에 오토메이티드 후안 도파초
/**
* Should loop over a task function which returns a "wrapper" object
* until wrapper.done is true. A seed value wrapper.seed is propagated to the
* next run of the loop.
*
* todo/maybe? Reject if wrapper is not an object with done and seed keys.
*
* @param {Promise|*} seed
* @param {Function} taskFn
*
* @returns {Promise.<*>}
*/
function seedLoop(seed, taskFn) {
const seedPromise = Promise.resolve(seed);
return seedPromise
.then(taskFn)
.then((wrapper) => {
if (wrapper.done) {
return wrapper.seed;
}
return seedLoop(wrapper.seed, taskFn);
});
}
// A super simple example of counting to ten, which doesn't even
// do anything asynchronous, but if it did, it should resolve to
// a promise that returns the { done, seed } wrapper object for the
// next call of the countToTen task function.
function countToTen(count) {
const done = count > 10;
const seed = done ? count : count + 1;
return {done, seed};
}
seedLoop(1, countToTen).then((result) => {
console.log(result); // 11, the first value which was over 10.
});