繁体   English   中英

如何设置对变量的Promise响应

[英]How do i set the response of a promise to a variable

我有一个异步函数返回一个值

  async getUsername(env:string,skuName: string,token:string): Promise<any> {
      let value =  await this.getDeviceName(env,skuName,token);
      return value;
  };

在另一个函数中,我将其称为“获取用户名”函数

let productN;
const prod = this.getUsername(env,skuName,token).then((resp) => {
    productN= resp;
    this.wait(300);
});

变量productN正在工作,因为我可以在日志中看到响应,但是当我尝试在此块之外使用productN时,我遇到了未定义的情况。

 promotion = { 
    name: productN,
    startDate: start,
    endDate: end
 };

我正在尝试将名称设置为productN,但我无法使其正常工作。

有人可以向我解释我做错了吗? 谢谢

您可以在收到回复后分配给promotion -

const prod = this.getUsername(env,skuName,token).then((resp) => {
    productN =  resp;
    promotion.name = resp
    this.wait(300);
});

由于您的getUsername是异步的,因此可以使用await响应,然后将其分配给promotion对象。

(async() => {
  const resp = await this.getUsername(env,skuName,token);
  promotion = {
    name: resp,
    startDate: start,
    endDate: end
  } 
})();

-编辑-

 const input = [ { env: 'lorem', skuname: 'skuname1', token: 'dummy' }, { env: 'lorem', skuname: 'skuname2', token: 'dummy' } ]; const getUserName = (username) => { return new Promise(resolve => { setTimeout(()=>resolve(username), 2000); }); }; (async () => { const resp = await Promise.all(input.map(({skuname}) => getUserName(skuname))); console.log(resp); })(); // Or Promise.all(input.map(({skuname}) => getUserName(skuname))) .then(resp => { console.log(resp); }); 

尝试

const productN = await this.getUsername(env,skuName,token);
console.log(productN);

你可以尝试这样做吗? getUsername返回您的getDeviceName函数;

getUsername(env:string, skuName: string, token:string): Promise<any> {
  return this.getDeviceName(env, skuName, token);
};
const productN = await this.getUsername(env, skuName, token);
console.log(productN);

我不知道您为什么使用getUsername 因为你可以得到价值productN直接从getDeviceName

喜欢

const productN = await this.getDeviceName(env, skuName, token);

如果要在getUsername内执行任何其他操作。 您可以使其兑现承诺。

getUsername(env:string, skuName: string, token:string): Promise<any> {
 return New Promise(async (resolve,reject)=>{
  try {
   let value =  await this.getDeviceName(env,skuName,token);
   ...
   //all other things you want to do here 
   ...
   resolve(value);
  } catch (error) {
   reject(error)
  }
 }
};

const productN = await this.getUsername(env, skuName, token);
console.log(productN);

nb:我使用try catch块进行错误处理,如果不想,请忽略它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM