gpt4 book ai didi

javascript - 如何在上一个结束后发起调度

转载 作者:行者123 更新时间:2023-11-30 11:10:45 24 4
gpt4 key购买 nike

首先,感谢您阅读我的问题并尝试帮助我并为我的英语道歉。

我正在使用 redux 和 redux-thunk,我想在 redux 上启动多个调度。更准确地说,我想在前一个结束后发起一个调度。

我的问题是我不知道如何在没有获取的情况下实现它。

例如:启动 dispatch1 -> 结束 dispatch1 -> 启动 dispatch2

这是我的代码:

static moveLayer(layerSelected, direction) {
const mapLayers = [... AxisStore.getStore().getState().map.mapGLlayers];
const ids = mapLayers.map(l => l.id);
const index = ids.indexOf(layerSelected.id);
let newIndex = direction === 'down' ? index - 1 : index + 1;

let layerUpdated = Object.assign({}, mapLayers[index], {
redraw: false
});
let oldPositionLayer = Object.assign({}, mapLayers[newIndex], {
redraw: false
});

if (direction === 'down') {
mapLayers.splice(newIndex, 2, layerUpdated, oldPositionLayer);
} else {
mapLayers.splice(index, 2, oldPositionLayer, layerUpdated);
}

return (dispatch) => {
dispatch({
type: MapTypeConstants.SET_MAP_LAYERS,
payload: mapLayers
});
};
}

static updateBefore(layer) {
let mapLayers = [... AxisStore.getStore().getState().map.mapGLlayers];
const ids = mapLayers.map(l => l.id);
const posInRedux = ids.indexOf(layer.id);
let nextVisibleLayer = mapLayers.find((layerObj, idx) => idx > posInRedux && layerObj.layout && layerObj.layout.visibility && layerObj.layout.visibility === 'visible');
mapLayers[posInRedux].before = (nextVisibleLayer) ? String(nextVisibleLayer.id) : undefined;
mapLayers[posInRedux].redraw = (mapLayers[posInRedux].layout.visibility === 'visible') ? true : false;
return (dispatch) => {
dispatch({
type: MapTypeConstants.SET_MAP_LAYERS,
payload: mapLayers
});
};
}

最佳答案

要等待异步调用结束,可以使用 JS 关键字 await。使用此关键字时,您的代码将暂停,直到您调用的 Promise 结束,您的函数现在也需要变为 async :

myFunction = async () => {
await dispatch({})
dispatch({})
}

除非第一个调度完成,否则不会调用您的第二个调度。

这是你唯一的方法,请看下面的评论

第二种选择是使用 Promise.all .它将按照您提交的顺序执行一系列 Promise:

myFunction = async () => {
await Promises.all([
dispatch({}),
dispatch({})
])
}

关于javascript - 如何在上一个结束后发起调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53829001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com