useEffect(() => {
new Promise(resolve => {
setTimeout(() => {
resolve();
/* 신규 로트번호 생성을 위한 다음 auto_increment 가져오기 */
axios
.get("http://localhost:8080/api/item/autoId")
.then(response => {
var output = response && response.data;
const newLote = lote;
newLote.lote = nowDate + "-" + output;
setLote(newLote);
})
.catch(response => {
console.log(response);
});
}, 600);
}),
new Promise(resolve => {
setTimeout(() => {
resolve();
//재고조회 (로트번호 검색기능)
axios
.get("http://localhost:8080/api/item/1")
.then(response => {
var output = response && response.data;
const newLookup = Object.assign({}, lookup);
for (var i = 0; i < output.list.length; i++) {
var value = output.list[i].lote_id;
newLookup.lookup[value] = value;
}
newLookup.lookup[lote.lote] = lote.lote;
setLookup(newLookup);
console.log(lookup.lookup);
const newState = Object.assign({}, state);
newState.columns[1].lookup = lookup.lookup;
setState(newState);
})
.catch(response => {
console.log(response);
});
}, 600);
}),
new Promise(resolve => {
setTimeout(() => {
resolve();
/* 출고 이력 불러오기 */
axios
.get("http://localhost:8080/api/shipping/history/1")
.then(response => {
var output = response && response.data;
const newState = Object.assign({}, state);
newState.data = output.list;
setState(newState);
})
.catch(response => {
console.log(response);
});
}, 600);
});
}, []);
函数组件中的useEffect ()函数如下所示。
下面总共有三个异步通信。
问题是,这些异步通信并不是每次都要经过相同的顺序。
如何进行异步通信,如代码所示?
发布于 2020-01-02 07:59:46
如果希望将输出严格排序为输入,则可以使用带有并发控制的P-队列队列。
useEffect(() => {
const myPromises = [
() =>
new Promise(resolve =>
setTimeout(() => {
resolve();
console.log("First(slow)");
}, 5000)
),
() =>
new Promise(resolve =>
setTimeout(() => {
resolve();
console.log("Second(fast)");
}, 100)
),
() =>
new Promise(resolve =>
setTimeout(() => {
resolve();
console.log("Third(slower)");
}, 10000)
)
];
queue.addAll(myPromises);
}, [queue]);
更新您的代码应该如下所示
useEffect(() => {
const myPromises = [
() =>
axios
.get("http://localhost:8080/api/item/autoId")
.then(x => console.log(x)),
() =>
axios
.get("http://localhost:8080/api/item/1")
.then(x => console.log(x)),
() =>
axios
.get("http://localhost:8080/api/shipping/history/1")
.then(x => console.log(x))
];
queue.addAll(myPromises);
}, [queue]);
发布于 2020-01-02 10:49:54
我相信你要找的是Promise chaining
。您可以使用Promise.all(),也可以这样做。下面的示例是使用诺言链接的一种方法。你可以用谷歌Promise chaining
来了解更多关于它的信息:)
axios.get('1st api call').then(res1 => {
//some code related to 1st
return axios.get('2nd api call')
}).then(res2 => {
//some other code related to 2nd
return axios.get('3rd api call')
}).then(res3 => {
//some other code related to 3rd
})
您可以删除那些看似不正确的setTimeouts
和new Promise
,并尝试这样的方法。上面的代码所做的是,在第一个API调用成功之后,调用第二个API调用,当第二个API调用成功时,调用第三个API调用。
希望我说的是你的问题,这有帮助!
https://stackoverflow.com/questions/59559168
复制相似问题