【问题标题】:Problems with Promise.allPromise.all 的问题
【发布时间】:2020-10-14 15:42:19
【问题描述】:

我必须回到这个论坛寻求帮助,因为我仍然无法让 'Promise.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 循环,之后我希望有一个 promise 数组:

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 部分仅在所有承诺都解决后才执行,并且还希望“响应”是来自上述各个承诺的所有 json 响应的列表。尽管如此,我还是得到了一串“未定义”。给人的印象是 .then 中的代码部分正在运行,即使承诺尚未解决。

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

【问题讨论】:

  • 您的 myFetch() 没有返回任何内容,您需要执行类似 return fetch(url).then(...); 的操作
  • .then里面有一个return
  • 你确定你所有的请求都给出了正确的响应,就像你承诺的失败一样。所有的都失败了
  • @Bob-it 返回不会返回到您的myFetch() 调用,而是返回到.then() 中提供的回调
  • 你可能是对的。现在我正在尝试两个“返回”,正如 Terry Lennox 的回答中所建议的那样,它似乎正在工作

标签: javascript promise


【解决方案1】:

你需要从 fetch 调用中返回 Promise,否则 Promise 链将被破坏,一旦你这样做,一切都应该很好!

这样的东西应该可以工作:

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

一个 sn-p 示例:

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();

【讨论】:

  • 感谢@terry-lennox,它有效。我曾尝试在 fetch 或 response 行中返回,但两者都没有!
  • 是的,我之前已经做过很多次了,但我已经摸不着头脑了:-D,我猜我们会从错误中吸取教训。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 2018-05-24
  • 2021-10-13
  • 2019-05-16
  • 2021-06-06
  • 1970-01-01
相关资源
最近更新 更多