为什么此异步函数中的代码会在之后触发?

时间:2017-12-28 07:07:29

标签: javascript async-await

在以下代码中:

  async createPanoramas ({ dispatch, commit, rootState }, newPanoramas = {}) {
    const { enterprise = '' } = rootState.route.query
    const splitNewPanoramas = []
    const clonedNewPanoramas = newPanoramas.panoramas.slice()

    while (clonedNewPanoramas.length) {
      splitNewPanoramas.push(clonedNewPanoramas.splice(0, MAX_ARRAY_EACH_API_CALL))
    }

    return splitNewPanoramas.forEach(async panoramasPayload => {
      const payload = {
        buildingId: newPanoramas.buildingId,
        panoramas: panoramasPayload
      }
      const urlEnd = '/v2/panoramas'
      const type = 'post'
      const resp = await api.asyncRequest(urlEnd, type, payload).catch(resp => {
      console.log('Before response')
      return resp
    })
  }

  // payload = [{"objectId":"2cd2244c-31bf-424b-831e-35360f422363","index":1},{"objectId":"012fd0f8-1bc9-4336-81fc-afd46836b0c9","index":2}]
  this.createPanoramas(payload).then(resp => {
    console.log('After then') 
  })

控制台日志'Before resp'将在'After then'之后触发。

这是为什么?以及如何修改异步功能,以便'Before resp'触发'After then'

1 个答案:

答案 0 :(得分:0)

您需要调整代码,因为它无效,但除此之外,您需要返回一组promise,然后等待所有这些代码完成。

const api = {
  asyncRequest() {
    return new Promise(resolve => setTimeout(() => {
      resolve();
    }, 500));
  },
};

async function createPanoramas(
  { dispatch, commit, rootState },
  newPanoramas = {}
) {
  const splitNewPanoramas = [{}, {}, {}];

  return splitNewPanoramas.map(async panoramasPayload => {
    const payload = {
      buildingId: newPanoramas.buildingId,
      panoramas: panoramasPayload
    };
    const urlEnd = "/v2/panoramas";
    const type = "post";
    const resp = await api.asyncRequest(urlEnd, type, payload).then(resp => {
      console.log("Before response");
    });
    return resp;
  });
}

payload = [
  { objectId: "2cd2244c-31bf-424b-831e-35360f422363", index: 1 },
  { objectId: "012fd0f8-1bc9-4336-81fc-afd46836b0c9", index: 2 }
];

const responses = createPanoramas(payload).then(responses => {
  Promise.all(responses).then(resp => {
    console.log("After then");
  }).catch(err => { console.log(err); });
});