【问题标题】:Promise, Async Await承诺,异步等待
【发布时间】: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 状态时,什么都没有改变。

我想知道如何将其变成 asyncawait 或单独使用 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


    【解决方案1】:

    您可以这样做(代码内嵌解释):

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

    【讨论】:

    • 完美!!!谢谢你,先生!这就像一个魅力,我真的不能感谢你,我一直在绞尽脑汁试图解决这个问题。
    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2018-03-05
    • 1970-01-01
    • 2020-03-26
    • 2018-12-24
    • 2023-04-06
    相关资源
    最近更新 更多