Javascript 承诺,异步等待
因此,我在这里遇到的问题是,Javascript 承诺,异步等待,javascript,asynchronous,async-await,es6-promise,Javascript,Asynchronous,Async Await,Es6 Promise,因此,我在这里遇到的问题是,onSetDevices(newDeviceList)get在devices.map()完成之前被调用。这是因为devices.map() 因为发生这种情况时,onSetDevices没有将newDevice包含在对象的newDeviceList数组中,并且当我使用onSetDevices设置redux状态时,没有任何更改 我想知道如何将此转换为异步、等待或仅使用承诺来完成使onSetDevices等待devices.map()完成的任务 下面是oncePostDev
onSetDevices(newDeviceList)
get在devices.map()完成之前被调用。这是因为devices.map()
因为发生这种情况时,onSetDevices
没有将newDevice
包含在对象的newDeviceList
数组中,并且当我使用onSetDevices
设置redux状态时,没有任何更改
我想知道如何将此转换为异步、等待或仅使用承诺来完成使onSetDevices
等待devices.map()
完成的任务
下面是oncePostDevice的代码:
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);
}
正如你所看到的,我已经承诺在这里工作并在之后返回数据
我只需要知道如何在我点击设置设备上的之前完成我的setDeviceTimeout
内部映射函数,以下是您可以做到的方法(在代码中内联解释):
完美的谢谢你,先生!这就像一个魅力,我真的非常感谢你,我一直在绞尽脑汁试图解决这个问题。
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()));
});
// 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);
};