gpt4 book ai didi

javascript - then 函数在所有异步调用执行之前执行

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

我正在调用后端服务来从 loadContent 方法的第一次获取中获取所有可用的 IDS,并且我正在从后端获取所有 IDS。

从初始服务中随机挑选 10 个 IDS,我分别调用另一个服务来获取 ID 的完整数据。我也能够获取所有数据,但在获取所有数据之前正在调用带有调度的函数,因此数据未在商店中设置。

export function loadContent(requestUrl) {
return dispatch => {

return fetch( /* initial calls to get all the ids */ ).then((response) => {
return response.json();
}).then((data) => {
console.log(data);
var stories = [];


var x = 0;
var loopArray = function(data) {
return customAlert(data, function() {


});
}

function customAlert(topStories, callback) {
var randomNumber = topStories[Math.floor(Math.random() * topStories.length)];
fetch( /* call service with individual id */ ).then((response) => {
return response.json();
}).then((output) => {
console.log(output);
stories[x] = output;
x++;

// any more items in array? continue loop
if (x <= 10) {
loopArray(data);
} else {
return stories;
}
})
}
return loopArray(data);
}).then((stories) => {
dispatch({
type: "LOAD",
payload: stories
});
}).catch((err) => {
console.log("There has been error");
})


};
}

export function load(news) {
return {
type: 'LOAD',
news: news
}
}

最佳答案

您需要从其内部 block 返回每个Promise,以便可以将它们全部链接在一起并获得.then((stories) 仅在全部完成后执行。即更改为:

return fetch( /* initial calls to

// ...

return customAlert(data, function() {

// ...

return fetch('to get the...

// ...

if (x <= 10) {
return loopArray(data);
}

这样初始调用

return loopArray(data);

只有在所有其他 Promise(现在与初始调用正确链接)解决后才会最终解决。

您还可以使用 push 来简化代码,例如:

stories.push(output);

而不是保留 stories 数组当前长度的 x 变量,以便可以分配给 stories[x]

此外,如果您能够并行进行 Promise,您可以考虑使用 Promise.all,以减少整个函数完成所需的时间。

关于javascript - then 函数在所有异步调用执行之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347216/

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