【问题标题】:How to wait for all Promise.all() to finish and then continue with the results如何等待所有 Promise.all() 完成然后继续结果
【发布时间】:2019-10-15 19:09:19
【问题描述】:

我知道这个问题不是这里第一个被问到的问题,但我尝试与其他 answers 合作,但我的代码没有按预期工作。我有一个 Promise.all 我有多个提取。获取的结果我变成了一个 json 然后继续。当一切都完成后,它应该打印“完成”,当然还有更多代码。但是,发生的情况是,“完成”被立即打印出来,然后一个接一个地输入获取的结果。

这是我的代码:

  Promise.all(selectedTypes.map((type) => {
    let body = {
      selectedScreenshot: type,
      dataUrl: dataUrl
    };
    fetch(URL, {
      method: 'POST',
      body: JSON.stringify(body),
      credentials: 'same-origin',
    })
    .then(resp => {
      console.log(resp.json()); //  this is done one by one as the results come in
      console.log('next');
    })
    }
  )).then(text => {
    console.log('done'); // this should be printed last, is printed first
  })

我做错了什么?

【问题讨论】:

  • .map() 回调没有返回任何内容 -> return fetch()
  • 在“内部”.then()中也没有return
  • @Andreas 你能告诉我如何添加返回值,以便 Promise.all() 完成,然后外部 .then() 打印一些东西吗?

标签: javascript promise fetch


【解决方案1】:

您需要返回fetch 并在fetch().then() 中返回一些结果,这里是Promise.all 的一些有用信息和示例

selectedTypes = ["https://jsonplaceholder.typicode.com/todos/1", "https://jsonplaceholder.typicode.com/todos/2"]; // My example
Promise.all(selectedTypes.map((type) => {
    let body = {
        //selectedScreenshot: type,
        //dataUrl: dataUrl
    };
    var URL = type;
    //You need to return the fetch
    return fetch(URL, {
        // method: 'POST',
        // body: JSON.stringify(body),
    }).then((resp) => resp.json()) // Transform the data into json
            .then(function (data) {
                console.log(data); //  this is done one by one as the results come in
                console.log('next');
                // you need to return the data
                return data;
            });
}
)).then(text => {
    text.forEach(function (item) {
        console.log('FROM PROMISE ALL');
        console.log(item);
    });
    console.log('done'); // this should be printed last, is printed first
});

例如,我添加了一些 json 链接,并评论了您问题中未声明的所有内容

【讨论】:

  • 您需要更多示例吗?简单地说,如果您不返回任何内容,则承诺已解决 Promise.all([function () { 2 + 2; }]).then(data => { console.log("resolved"); });
猜你喜欢
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 2019-04-08
  • 2015-10-04
相关资源
最近更新 更多