gpt4 book ai didi

javascript - 如何按顺序运行多个函数,并在其中任何一个函数失败时停止所有函数?

转载 作者:行者123 更新时间:2023-12-01 02:55:15 25 4
gpt4 key购买 nike

我有多个 Javascript 函数,每个函数都会执行一些 DOM 操作,然后运行 ​​ajax 请求。我希望能够运行第一个函数,它操作 DOM,然后触发其 ajax 请求,然后,当 ajax 请求完成时,如果 ajax 请求返回 true,我想运行第二个函数,或者停止执行其余的函数函数并执行一些其他 DOM 操作(例如显示错误消息)。

我希望这些函数依次运行,一个接一个,并且只有在它们都没有从 ajax 请求中返回 false 时才继续运行。如果它们都没有返回 false,那么它们都应该运行,最终我会在“always”回调中进行一些操作。

我怎样才能做到这一点?

我的第一个想法是使用 Promise,以保持代码简洁,但经过几个小时的阅读后,我就是不知道如何实现这一点。

下面是我当前的代码,这是我在执行时在控制台中得到的内容:

inside test1
inside test2
inside test3
fail
[arguments variable from fail method]
always
[arguments variable from always method]

这就是我想要在控制台中得到的内容(注意缺少的“inside test3”字符串):

inside test1
inside test2
fail
[arguments variable from fail method]
always
[arguments variable from always method]

代码如下:

(function($) {
var tasks = {
init: function() {
$.when(
this.test1(),
this.test2(),
this.test3()
).done(function() {
console.log('done');
console.log(arguments);
})
.fail(function() {
console.log('fail');
console.log(arguments);
})
.always(function() {
console.log('always');
console.log(arguments);
});
},

test1: function() {
console.log('inside test1');
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
},

test2: function() {
console.log('inside test2');
// note the misspelled "typ" arg to make it fail and stop execution of test3()
return $.getJSON('https://baconipsum.com/api/?typ=meat-and-filler');
},

test3: function() {
console.log('inside test3');
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
}
};

tasks.init();
})(jQuery)

有什么想法吗?

最佳答案

使用 Promise 确实使代码更加简洁

注意:Promise/A+ Promise .then 和 .catch 回调仅接受一个参数,因此无需查看参数,只需使用单个参数

这段代码(ES2015+)显示了多么简单

let p = Promise.resolve();
Promise.all([this.test1, this.test2, this.test3].map(fn => p = p.then(fn()))).then(allResults =>

或者,使用 array.reduce

[this.fn1, this.fn2, this.fn3].reduce((promise, fn) => promise.then(results => fn().then(result => results.concat(result))), Promise.resolve([])).then(allResults =>

在这两种情况下,allResults 都是来自 testN 函数的(已解析)结果数组

它创建一个(已解决的) promise 来“启动” promise 链

Array#map 链接每个函数(this.test1 等),以在前一个结果的 .then 中执行。每个 this.testn Promise 的结果都在一个新数组中返回,该数组是 Promise.all

的参数

如果 testN 中的任何一个失败,则不会执行下一个

var tasks = {
init () {
let p = Promise.resolve();
Promise.all([this.test1, this.test2, this.test3].map(fn => p = p.then(fn())))
.then(results => {
console.log('done');
console.log(results);
return results; // pass results to next .then
}).catch(reason => {
console.log('fail');
console.log(reason);
return reason; // because I return rather than throw (or return a Promise.reject),
//the next .then can will get `reason` in it's argument
}).then(result => {
console.log('always');
console.log(result);
});
},
test1() {
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
},
test2() {
return $.getJSON('https://baconipsum.com/api/?typ=meat-and-filler');
},
test3() {
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler').then(result => {
if(someCondition) {
throw new Error("sum ting wong");
// or
return Promise.reject(new Error("sum ting wong"));
}
return result;
});
}
};
tasks.init();

对于问题中的代码,你可以进一步简化

var tasks = {
init () {
let p = Promise.resolve();
const urls = [
'https://baconipsum.com/api/?type=meat-and-filler',
'https://baconipsum.com/api/?typ=meat-and-filler',
'https://baconipsum.com/api/?type=meat-and-filler'
];
Promise.all(urls.map(url => p = p.then(() => $.getJSON(url))))
.then(results => {
console.log('done');
console.log(results);
return results; // pass results to next .then
}).catch(reason => {
console.log('fail');
console.log(reason);
return reason; // because I return rather than throw (or return a Promise.reject),
//the next .then can will get `reason` in it's argument
}).then(result => {
console.log('always');
console.log(result);
});
}
};
tasks.init();

关于javascript - 如何按顺序运行多个函数,并在其中任何一个函数失败时停止所有函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46740297/

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