[英]Promise, Async Await
setDeviceTimeout = id => timeout => {
const {onSetDevices, devices} = this.props;
var newDeviceList = devices.map(device => {
if (device.id === id) {
var newDevice = {
//...device,
timeout: timeout
};
deviceTable.oncePostDevice(newDevice).then( data => {
return newDevice = data
});
}
return device;
});
onSetDevices(newDeviceList);
}
所以我在這里的問題是在devices.map()
完成之前調用了onSetDevices(newDeviceList)
。 這是因為devices.map()
具有對服務器的調用oncePostDevice(newDevice)
,然后返回數據並將其存儲在newDevice
變量中並將其放入newDeviceList
數組中。
因為這種情況onSetDevices
不包括在newDevice
中newDeviceList
對象的數組,當我設置用我的終極版狀態onSetDevices
,一切都沒有改變。
我想知道如何將其轉換為async , await或單獨使用promise來完成使onSetDevices
等待devices.map()
完成的任務。
這也是oncePostDevice
的代碼:
export const oncePostDevice = (device) => new Promise(function(resolve, reject) {
fetch('https://url/devices/'+device.id, {
method: 'PUT',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(device)
})
.then(response => response.json())
.then(
data => {return resolve(data)},
error => {return reject(error)}
)
.catch(err => console.error(this.props.url, err.toString()));
});
如您所見,在這里工作並隨后返回數據,我已經有了一個承諾 。
我只需要知道如何使我的setDeviceTimeout
內部映射函數完成,然后再點擊onSetDevices
。
這是您的操作方法(代碼內聯說明):
// make the function async
setDeviceTimeout = id => async timeout => {
const {onSetDevices, devices} = this.props;
// make a list of promises, not of devices
// note: mapping a value via an async function will create promises
const newDeviceListPromises = devices.map(async device => {
if (device.id === id) {
const newDevice = {
...device,
timeout: timeout
};
return await deviceTable.oncePostDevice(newDevice);
}
return device;
});
// wait for all promises to finish and what they return will be the devices
const newDeviceList = await Promise.all(newDeviceListPromises);
onSetDevices(newDeviceList);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.