微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何一个接一个地解决承诺?

我怎么能一个一个地解雇承诺呢?

waitFor(t),是一个返回在t时间后解析的promise的函数.我希望能做的是:

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秒接一次,这意味着所有的一次调用的承诺.

我设法用这样的回调解决了这个问题,但这使得一切都变得非常丑陋:

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/

解决方法:

我找到了你的解决方

然后你需要让每个人都返回一个新的诺言,这样下一次就可以在前一个答案得到解决后做出反应.

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] 举报,一经查实,本站将立刻删除。

相关推荐