如何兑现承诺?

最高

我如何才能一次又一次地兑现承诺?

waitFor(t),是一个返回承诺的函数,该承诺会在t一段时间后解决我希望能够做到的是:

waitFor(1000) Then when finished, console.log('Finished wait of 1000 millis') then
waitFor(2000) Then when finished, console.log('Finished wait of 2000 millis') then
waitFor(3000) Then when finished, console.log('Finished wait of 3000 millis')

这是我尝试过的:

waitFor(1000).then(function(resolve, reject) {
    console.log(resolve);
}).then(waitFor(2000).then(function(resolve, reject) {
    console.log(resolve);
})).then(waitFor(3000).then(function(resolve, reject) {
    console.log(resolve);
}));

不幸的是,这个console.logs每隔1秒记录一次语句,这意味着Promise会立即被调用。

我设法通过回调来解决此问题,但是这使所有事情变得非常难看:

waitFor(1000).then(function(resolve, reject) {
    console.log(resolve+' @ '+(new Date().getSeconds()));
    waitFor(2000).then(function(resolve, reject) {
        console.log(resolve+' @ '+(new Date().getSeconds()));
        waitFor(3000).then(function(resolve, reject) {
            console.log(resolve+' @ '+(new Date().getSeconds()));
        });
    });
});

那么,我该如何使用使它起作用的诺言来做到这一点,却不使用丑陋的回调地狱呢?

不良结果:http//jsfiddle.net/nxjd563r/1/

所需的结果:http : //jsfiddle.net/4xxps2cg/

蒂亚戈·罗梅罗·加西亚

我找到了您的解决方案。

您需要让每个人then都返回一个新的承诺,以便下一个承诺then一旦解决,下一个就可以做出反应。

waitFor(1000).then(function(result) {
    $('#result').append(result+' @ '+(new Date().getSeconds())+'<br>');
    return waitFor(2000);
}).then(function(result) {
    $('#result').append(result+' @ '+(new Date().getSeconds())+'<br>');
    return waitFor(3000);
}).then(function(result) {
    $('#result').append(result+' @ '+(new Date().getSeconds())+'<br>');
});

jsfiddle http://jsfiddle.net/4xxps2cg/2/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章