承诺,异步等待

时间:2018-03-19 15:10:13

标签: javascript asynchronous async-await es6-promise

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)devices.map()完成之前被调用了。这是因为devices.map()调用了服务器oncePostDevice(newDevice),然后返回数据并将其存储在newDevice变量中并将其放入newDeviceList数组中。

因为发生这种情况onSetDevices不包含newDevice对象数组中的newDeviceList,当我使用onSetDevices设置我的redux状态时,没有任何变化。

我想知道如何将其转换为 async 等待或单独使用 promise 来完成制作{{1}的任务等待onSetDevices完成。

此处还有devices.map()的代码:

oncePostDevice

正如您所看到的,我已经在这里工作了 promise ,然后返回数据。

我只需要知道在点击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内部映射功能。

1 个答案:

答案 0 :(得分:0)

以下是如何做到的(代码内联说明):

// 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);
};