离子2承诺 - 在执行第二个过程之前完成第一个过程



对于我的离子2项目,我有两个函数,一个又一次执行。每个功能都由一个API调用组成。我想等到第一个函数完成执行所有内容后才进入第二个功能。

我遇到的问题是,由于第一个功能需要一些时间才能完成,因此第二个功能在执行第一个功能之前执行。

我正在学习如何使用承诺,因为我被告知它可以解决这个问题。我简化了代码,因此更容易遵循:

const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });
  return new Promise((resolve, reject) => {
    resolve();
  });
};
const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {
  });
  return new Promise((resolve, reject) => {
    resolve();
  });
};
first().then(() => {
  return second();
});

您可以将帖子包装在new Promise中:

const first = () => {
    return new Promise((resolve, reject) => {
        self.pspService.post('/api/Conversation/GetPersonalCalendarData', {
            }, result => {
                result.Data.forEach(lAppointment => {});
                resolve();
            });
    });
};
const second = () => {
return new Promise((resolve, reject) => {
    self.pspService.post('/api/Conversation/AddPersonalAppointment', {
        }, result => {
            resolve();
        });
});
};
first().then(() => {
     return second();
});

或直接返回邮政生成的承诺

const first = () => {
    return self.pspService.post('url, {}, result => {
            result.Data.forEach(lAppointment => {});
            return Promise.resolve(result);
        })
}

使用新的httpclient和switchmap获取唯一可观察的

firstAndSecond(){
    return self.pspService.post('/api/Conversation/GetPersonalCalendarData')
          .switchMap((data:any)=>{
            //there you have "data", you can use to change the post
            return self.pspService.post('/api/Conversation/AddPersonalAppointment')
           });
}
//In your component
myService.firstAndSecond().subscribe((data2)=>{
    //data2 it's only the data from self.pspService.post
}

您可以使用 async /等待来处理这种情况。>关键字;等待暂停执行,直到实现异步函数返回承诺并从返回的承诺中解开值。

async func(){
    const first = () => {
      self.pspService.post('/api/Conversation/GetPersonalCalendarData',
        {
        }, result => {
          result.Data.forEach(lAppointment => {
          });
        });
      return new Promise((resolve, reject) => {
        resolve();
      });
    };
    const second = () => {
      self.pspService.post('/api/Conversation/AddPersonalAppointment', {
      }, result => {
      });
      return new Promise((resolve, reject) => {
        resolve();
      });
    };
    let firstValue = await first();
    console.log("First Value", firstValue);
    let secondValue = await second();
    console.log("Second Value", secondValue);
  }

相关内容

  • 没有找到相关文章

最新更新