Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我们能在那时得到当前的承诺吗?_Javascript_Loops_Recursion_Promise - Fatal编程技术网

Javascript 我们能在那时得到当前的承诺吗?

Javascript 我们能在那时得到当前的承诺吗?,javascript,loops,recursion,promise,Javascript,Loops,Recursion,Promise,我想有一些机制来重做,然后在承诺中发挥作用。继续做,直到它通过一些检查 somePromise.then(() => { if(state == "finish") return; // DoSomething async then repeat these codes // could we do it by [return this;] ? }).then(() => console.log("finish")); 通常,您无法访问.t

我想有一些机制来重做,然后在承诺中发挥作用。继续做,直到它通过一些检查

somePromise.then(() => {
    if(state == "finish")
        return;

    // DoSomething async then repeat these codes
    // could we do it by [return this;] ?
}).then(() => console.log("finish"));

通常,您无法访问
.then()
处理程序中的当前承诺。而且,在大多数情况下,你无法做任何有用的事情。添加另一个
.then()。一旦兑现,承诺永远不会改变其状态

如果要重复某个操作,可以从要重复的操作中生成一个函数,然后从
处理程序中再次调用它。然后()
处理程序返回结果承诺(从而将其链接到以前的承诺)

下面是一个例子:

// utility delay function that returns a promise
function delay(t, val) {
   return new Promise(function(resolve) {
       setTimeout(function() {
           resolve(val);
       }, t);
   });
}

// repeatedly call someAsyncOp() until we see the operation is finished
function repeatUntil(t) {
   return someAsyncOp().then(function(state) {
      if (state !== "finish") {
           return delay(t).then(repeatUntil);
      }
   });
} 

// sample usage
repeatUntil(5000).then(function() {
    // state is finished here
}).catch(function(err) {
    // error here
});

您可以命名在
处使用的函数。然后()
,在
处递归调用相同的函数。
doSomethingAsync()
的然后()
调用,直到
状态==“finish”


另请参见

var retry=fn=>=>fn().catch(retry(fn))-并在检查失败时进行fn抛出。。。用法:
retry(fn).then(ok=>console.log(ok))等等,你想重新运行
somePromise。然后(()=>{
如果第一个
中的某些条件得到满足,那么
就满足了?谢谢。我用lambda作为回调太多了,直到我忘了我们可以命名回调。这很好
// name function used at `.then()` 
somePromise.then(function re(data) {
    if(state == "finish") {
        return data;
    };
    // DoSomething async then repeat these codes
    // call `re` at `.then()` chained to `doSomethingAsync()`
    doSomethinAsync(data).then(re);
}).then((data) => console.log("finish", data));