【发布时间】:2018-03-19 23:24:04
【问题描述】:
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);
}
所以我在这里遇到的问题是 onSetDevices(newDeviceList) get 在 devices.map() 完成之前被调用。这是因为devices.map() 调用了服务器oncePostDevice(newDevice),然后返回数据并将其存储在newDevice 变量中,并将其放入newDeviceList 数组中。
因为发生这种情况 onSetDevices 不包括 newDevice 对象数组中的 newDeviceList 并且当我使用 onSetDevices 设置我的 redux 状态时,什么都没有改变。
我想知道如何将其变成 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()));
});
如您所见,我已经承诺在这里工作并在之后返回数据。
我只需要知道如何在我点击onSetDevices 之前完成我的setDeviceTimeout 内部映射函数。
【问题讨论】:
标签: javascript asynchronous async-await es6-promise