如何使用promise计划多个功能,我是否应该像2
那样嵌套回调?
在服务器端,我使用nodejs
和co
制作生成器,
然后让它看起来像下面
co(function *() {
yield q1();
yield q2();
yield q3();
...
是否有一些类似的带有承诺的语法?
var q1 = function() {
return new Promise(function (fulfill, reject){
setTimeout(function(){
fulfill(console.log('q1'));
}, 100);
});
};
var q2 = function() {
return new Promise(function (fulfill, reject){
setTimeout(function(){
fulfill(console.log('q2'));
}, 100);
});
};
var q3 = function() {
console.log("done!");
};
1
q1().then(function() {
q2();
}).then(function() {
q3();
});
2
q1().then(function() {
q2().then(function() {
q3();
});
});
答案 0 :(得分:2)
使用您已获得的代码,您可以简单地执行此操作
q1().then(q2).then(q3);
答案 1 :(得分:1)
从当时的回调中返回承诺,如
var q1 = function() {
return new Promise(function(fulfill, reject) {
setTimeout(function() {
snippet.log('q1')
fulfill();
}, 1000);
});
};
var q2 = function() {
return new Promise(function(fulfill, reject) {
setTimeout(function() {
snippet.log('q2')
fulfill();
}, 1000);
});
};
var q3 = function() {
snippet.log("done!");
};
q1().then(function() {
return q2();
}).then(function() {
q3();
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>