提问者:小点点

Promission.All的问题


我必须回到这个论坛寻求帮助,因为我不能仍然使‘承诺.所有’工作!

第一,我有这个函数,按说是回一个承诺:

const myFetch = (a, b) => {
    var url;
    // some stuff bulding 'url' using a and b
    fetch(url).then(response => {
        return response.json();
    }
})

其思想是上面的函数返回一个promise,其值一旦解析,就是json对象。我已经检查了json实际上是有效的。如果我用下面的行替换“return...”行,我实际上会得到一个有效的JSON:

response.json().then(res=> console.log(res))

第二,我有这个for循环,之后我希望有一系列承诺:

promises = [];
for (...){
    // some other stuff
    promises.push(myFetch(a, b))
}

最终我执行以下代码:

Promise.all(promises)
.then(responses => { // <=== Here I get all "undefined"
    responses.forEach(response => {
        console.log(response);// <=== Here I get all "undefined"
    });
    // some other stuff that I can do only after all fetches are complete
})

我希望.then部分只在所有承诺都解决之后才执行,并且希望“responsions”是上面各个承诺的所有json响应的列表。尽管如此,我还是得到了一串“未定义”。给人的印象是.then中的代码部分正在运行,即使承诺尚未解决。

我做错了什么?在继续操作之前,我如何确保从各个提取中获得所有json对象?(注意,我不能使用Await/Async)。谢谢


共1个答案

匿名用户

你需要从fetch调用中返回承诺,否则承诺链将被打破,一旦你这样做了,所有人都应该玩得很好!

类似这样的事情应该起作用:

const myFetch = (a, b) => {
    var url;
    // some stuff bulding 'url' using a and b
    return fetch(url).then(response => {
        return response.json();
    })
};

一个片段示例:

null

const myFetch = (url, a, b) => {
  return fetch(url).then(response => {
    return response.json();
  })
};

function testMyFetch() {
    promises = [];
    for(let i = 0; i < 5; i++) {
        promises.push(myFetch("https://jsonplaceholder.typicode.com/users/" + (i+1)));
    }
    Promise.all(promises).then(result => console.log("Promise.all result:", result));
}
testMyFetch();