做一個函數來獲得解決了所需的時間承諾:
const delay = ms => new Promise(resolve => {
setTimeout(resolve, ms);
});
等待它和你的操作來完成:
someFunction(someService) {
return Promise.all([getDataFromBackend(), delay(500)]).then(([data]) => {
someService.makeAnAction();
});
}
替代不破壞結構,與藍鳥:
someFunction(someService) {
const dataGet = getDataFromBackend();
return delay(500).return(dataGet).then(data => {
someService.makeAnAction();
});
}
潛在誤導性等同於上述內容:
someFunction(someService) {
return delay(500)
.return(getDataFromBackend())
.then(data => {
someService.makeAnAction();
});
}
異步/等待:
async someFunction(someService) {
const dataGet = getDataFromBackend();
await delay(500);
const data = await dataGet;
someService.makeAnAction();
}
商店getDataFromBackend的'的返回值()'在超時以外的變量,然後把'.then'超時內調用。 – 4castle
這個問題有什麼問題? –
@ 4castle對我來說不是那麼明顯,謝謝。我會將其標記爲答案。 –