gpt4 book ai didi

javascript Promise 调度多个函数

转载 作者:行者123 更新时间:2023-11-28 19:04:44 24 4
gpt4 key购买 nike

如何使用 Promise 调度多个函数,我是否应该像 2 那样嵌套回调?
在服务器端我使用nodejsco生成生成器,然后让它看起来像下面这样

co(function *() {
yield q1();
yield q2();
yield q3();
...

是否有一些与 Promise 类似的语法?

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();
});
});

最佳答案

使用您拥有的代码,您可以简单地执行此操作

q1().then(q2).then(q3);

关于javascript Promise 调度多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com