gpt4 book ai didi

javascript - 使用 javascript promise 链以获得真正异步函数序列的最佳方法?

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

我读过一篇文章:https://javascript.info/promise-chaining这解释了一些使用 Promise 的好方法。

但是,如果我要运行多个函数,但每个函数只能在前一个函数完全完成后才开始,我不确定应该使用哪种方法。

从文章的第一个示例中获取并修改(主要是通过从解析中删除 setTimeout),这足以完成我所描述的操作吗?

new Promise(function(resolve, reject) {

resolve();

}).then(function() {

// first function here

}).then(function() {

// second function here

}).then(function() {

// third function here

});

或者我必须做本文后面描述的“返回 promise ”的事情,如下所示?

new Promise(function(resolve, reject) {

resolve();

}).then(function() {

// first function here

return new Promise((resolve, reject) => {
resolve();
});

}).then(function() {

// second function here

return new Promise((resolve, reject) => {
resolve();
});

}).then(function() {

// third function here

});

或者,有没有更简单或更好的方法来实现我想要的?

最佳答案

如果您在then中创建函数回调,

.then(
function() { // function callback
// some code
}
)

你不需要返回新的Promise,你可以只返回一些值,默认情况下该值将被包装到Promise

坏处:

.then(function() {
return new Promise((resolve, reject) => { // NOT need to create promise
resolve(1)
})
})

好:

.then(function() {
return 1; // in `than` function callback by default return new promise
})

关于javascript - 使用 javascript promise 链以获得真正异步函数序列的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52047241/

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