gpt4 book ai didi

javascript - 将嵌套 AJAX 调用转换为顺序 Promise

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

我的代码可以成功地按顺序运行 AJAX 调用(对我的员工进行粗略的互联网延迟测试):

const start = new Date().getTime();
const testUrl = "our server URL";
const start = new Date().getTime();
$.ajax(testUrl + '?delay=0.0&length=100').done(function(){
$.ajax(testUrl + '?delay=0.1&length=1000').done(function(){
$.ajax(testUrl + '?delay=0.2&length=10000').done(function(){
$.ajax(testUrl + '?delay=0.1&length=100000').done(function(){
$.ajax(testUrl + '?delay=0.2&length=10000').done(function(){
$.ajax(testUrl + '?delay=0.1&length=1000').done(function(){
$.ajax(testUrl + '?delay=0.0&length=100').done(function(){
$.ajax(testUrl + '?delay=0.1&length=10').done(function(){
const end = new Date().getTime();
internetTestTime = end - start;
console.log('Your internet test time: ' + internetTestTime + 'ms')
})
})
})
})
})
})
})
});

我想将其切换为使用按顺序运行的 Promise。以下是迄今为止的进展:

const start = new Date().getTime();
const testSuiteInputs = [
{delay: 0.5, length: 100},
{delay: 0.4, length: 500},
// more tests here
];
let testSequence = Promise.resolve();
testSuiteInputs.forEach(testSuiteInput => {
// 🌟 something goes here...
});
testSequence.then(() => {
const end = new Date().getTime();
internetTestTime = end - start;
console.log('Your internet test time: ' + internetTestTime + 'ms')
});

我需要在上面的 🌟 中添加什么才能使这些 Promise 顺序运行?

最佳答案

嗯,最简单的方法是将 .forEach() 循环切换为 async 函数内的普通 for 循环,然后使用等待:

async function run() {
const start = new Date().getTime();
const testSuiteInputs = [
{delay: 0.5, length: 100},
{delay: 0.4, length: 500},
// more tests here
];
for (let item of testSuiteInputs) {
let url = `${testUrl}?delay=${item.delay}&length=${item.length}`;
let result = await $.ajax(url);
// process result here
}
}

run().then(finalResult => {
console.log("all done");
}).catch(err => {
console.log(err);
});
<小时/>

要在不使用 async/await 的情况下实现此目的,对数组进行异步访问排序的常见设计模式是使用 .reduce(),只需将 Promise 链接在一起即可:

const start = new Date().getTime();
const testSuiteInputs = [
{delay: 0.5, length: 100},
{delay: 0.4, length: 500},
// more tests here
];

testSuiteInputs.reduce((p, item) => {
return p.then(() => {
// when previous ajax call finished, start the next one
let url = `${testUrl}?delay=${item.delay}&length=${item.length}`;
return $.ajax(url).then(result => {
// process individual result here
});
});
}, Promise.resolve()).then(finalResult => {
console.log("all done");
}).catch(err => {
console.log(err);
});;

关于javascript - 将嵌套 AJAX 调用转换为顺序 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60836991/

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