sourcecode

비동기 Vuex 액션을 2회 실행할 경우 콜 대기 후 코드를 랜덤 순서로 실행할 수 있습니까?

copyscript 2022. 8. 1. 22:41
반응형

비동기 Vuex 액션을 2회 실행할 경우 콜 대기 후 코드를 랜덤 순서로 실행할 수 있습니까?

const actions = {
  search: debounce(
    async ({ commit, dispatch, getters, rootGetters }, { page = 1 }) => {
      commit("setLoading", true);
      commit("setPage", page);

      console.log("Starting...")
      const randId = Math.random() * 100;
      console.log(randId);

      const results = await EventApi.get();

      console.log("Done: ", randId, `|${results.meta.slept}|`)

      // After `await`
      commit(page == 1 ? "setEvents" : "addEvents", results.events);
      // ... and a bunch more commits after that.

    }, 300, { leading: true, trailing: true })
  }
}

위의 액션이 두 번 호출된 경우:

store.dispatch('search', { page: 1 });
store.dispatch('search', { page: 1 });

첫 번째 콜의 요구가 완료되기까지 10초가 걸리고 두 번째 콜의 요구가 1초밖에 걸리지 않는다고 가정합니다.

코드는 다음입니까?await EventApi.get()번째 콜에서 실행된 두 번째 콜에서 요구가 훨씬 더 일찍 끝났어야 했다고 생각했을까요?난 그렇게 생각하지 않았을 텐데, 내 실험 결과 그게 사실이었으니, 내 코드에 뭔가 문제가 있는 게 틀림없어.

다음은 Vuex 로그 + 제 코멘트입니다.

https://gist.github.com/niuage/9e2dcd509dc6d5246b3a16af56ccb3d3


도움이 될 수 있도록 간단한 EventApi 모듈을 소개합니다.

const get = async () => {
  const q = await fetch(someUrl);
  const result = await q.json();

  return result;
}

export default {
  get
}

매우 드물게 결과 카운트가 실제 표시된 결과와 동기화되지 않는 문제가 있기 때문에 여러 요청 간에 레이스 조건이 있기 때문일 수 있다고 추측했습니다.

이 예에서 두 번째 짧은 콜이 먼저 완료됩니다.이것은, 그 이유는,await의 컨텍스트 내에서만 대기합니다.async기능.

부터async/await는 약속을 작성하는 다른 방법입니다.약속을 반환하는2개의 개별 함수 호출이라고 생각할 수 있습니다.하나는 다른 하나를 지연시키지 않을 것이다.

데모를 소개합니다.

const delay = time => new Promise(resolve => setTimeout(() => resolve(), time))

async function wait(id, time) {
  await delay(time);
  console.log(id + ' complete.');
}

console.log('Starting 1...');
wait('#1', 5000);
console.log('Starting 2...');
wait('#2', 1000);
View the bottom portion of the demo for the console results.

여기 있습니다.async로 작성된 위의 데모에서 기능하다.then대신:

function wait(id, time) {
  return delay(time).then(() => {
    console.log(id + ' complete.');
  });
}

이 예에서 두 번째 함수 호출이 첫 번째 함수 호출을 강제로 대기시키는 경우 두 개의 호출 컨텍스트를 모두 호출 컨텍스트로 만듭니다.async예를 들어 다음과 같습니다.

async created() {
  // Assuming the `search` action returns its http promise!
  await this.$store.dispatch('search', { page: 1 });
  await this.$store.dispatch('search', { page: 1 });
  ...
}

언급URL : https://stackoverflow.com/questions/66186336/if-an-async-vuex-action-is-run-twice-can-the-code-following-the-await-call-be-r

반응형