通过map运行后,从React JS中的promise中获取变量数据/结果

问题描述

我想要最后一个内部的activeCustomers数组的结果,但是我一直收到一条错误消息,指出箭头函数期望返回。不确定如何获得activeCustomers?

const CreateCustomer = (storeData) => {
  let activeOrganization = null;
  storeData.Org
    .getOrganization()
    .then(function createCustomer(organization) {
      activeOrganization = organization[0];

      const dataArray= storeData.attributes;
      activeOrganization 
        .createAttributes(
          attributeType[0],getSomeData(dimensions)
        )
        .then(function Properties(createdAttribute) {
          updateCustomerProperty(createdAttribute,attributeType[0]);
        });
       activeOrganization 
        .createAttributes(
          attributeType[1],attributeType[1]);
        });
     }).then(() => {
      activeOrganization
        .getCustomers()
        .then((cusomters) => {
          const activeCustomers = [];
          cusomters.map((customer) => {
            activeCustomers.push(customer);
          });
          return activeCustomers;
        })
        .then((activeCustomers) => {
          console.log(activeCustomers);
        });
    });
};

//Now I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
    

我想要最后一个内部的activeCustomers数组的结果,但是我一直收到一条错误消息,指出箭头函数期望返回。不确定如何获得activeCustomers?

解决方法

在您的示例中,我认为您收到了警告。但是仍然如何访问activeCustomers取决于您要如何使用它以及存储它的方式。

如果您想将其存储在全局范围内,则可以像这样存储它

let activeCustomers;
....
.then((cusomters) => {
          activeCustomers = [];
          cusomters.map((customer) => {
            activeCustomers.push(customer);
          });
          return activeCustomers;
        })

但是我认为最好重写为异步/等待。

const CreateCustomer = async (storeData) => {
  let activeOrganization = null;
  const [activeOrganization] = await storeData.Org
    .getOrganization();

  const activeOrgPrs = attributeType.map(x => activeOrganization 
        .createAttributes(
          x,getSomeData(dimensions)
        )));

  const attrs = await Promise.all(activeOrgPrs);

  attrs.forEach((attr,i) => {
      updateCustomerProperty(attr,attributeType[i]);
   })
  
   const cusomters = await activeOrganization
        .getCustomers();
   return cusomters;
};

您可以像const customers = await CreateCustomer(someData);一样使用它 或像CreateCustomer(someData).then((cusomters) => { activeCustomers = cusomters; return null;(if it keeps to return errors)});

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...