search

Home  >  Q&A  >  body text

javascript - Problem with promises received by await in async/await

In async/await, what await needs to receive is a promise object, then I write like this:

async getAddressList () {
        this.list = await AreaSvr.getList(320100);
      }

getAddressList().catch((err) => {
    ...
  });
AddressSvr.getList = function (pid) {
  return new Promise((resolve, reject) => {
    Vue._http.get('area/get', {pId: pid}).then(
      res => {
        resolve(res.Data);
      }, err => {
        reject(err);
      });
  })
};

There is no problem in this. AreaSvr.getList returns a promise object. Now I encapsulate AreaSvr.getList and add a cache:

let areaList = [];

AddressSvr.getAreaList = (level, pid) => {
// 接收等级跟pid两个参数,如果已有areaList或者相关二级list,直接返回Promise.resolve(...) 

  if (level === 1 && areaList.length !== 0) {
    return Promise.resolve(areaList)
  } else if (level === 2) {
    for (let i = 0; i < areaList.length; i++) {
      if (areaList[i].AreaId === pid && areaList[i].children.length !== 0) {
        return Promise.resolve(areaList[i].children)
      }
    }
  }
  
  // 这里对之前的http请求AddressSvr.getList进行封装,在获取到相关值之后,进行缓存并且返回
  
  return new Promise(// 返回一个promise对象,让await来接收
    (resolve, reject) => {
      AddressSvr.getList(pid).then(
        res => {
          if (level === 1) {
            areaList = res;// 缓存areaList 
            return resolve(areaList); //返回
          }
          for (let i = 0; i < areaList.length; i++) {
            if (areaList[i].AreaId === pid) {
              areaList[i].children = res;// 缓存子列表
              return resolve(areaList[i].children);// 返回
            }
          }
        }, err => {
          reject(err);
        }
      );
    }
  );
};
      
 async getAddressList () {
        this.list = await AreaSvr.getAreaList(1, 320100);//这里传入等级,使用加了缓存的函数
        if (this.list.length !== 0) {
          this.childList = await AreaSvr.getAreaList(2, this.list[0].AreaId);
        }
      }

Here, I encapsulated a layer of promise outside AddressSvr.getList for caching. At this time, await receives the promise returned by the AddressSvr.getAddressList function. However, the promise returned at this time is invalid and the error is directly caught. Okay, could you please tell me where I wrote something wrong?

曾经蜡笔没有小新曾经蜡笔没有小新2782 days ago809

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:40:44

    If it is caught directly, it means that there is no problem with the writing method. It may be that there is an error in the business part. You can post the error information and take a look

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:40:44

    I used areaList[i].children.length !== 0 to determine whether there is cache above. At this time, there are no children yet and it is undefind, so an error will be reported. This is not a usage problem of async/await, it's a mistake on my part.

    reply
    0
  • Cancelreply