Javascript 在响应前一个参数后执行函数

Javascript 在响应前一个参数后执行函数,javascript,angular,asynchronous,async-await,async.js,Javascript,Angular,Asynchronous,Async Await,Async.js,我试图在返回前一个函数的成功响应后执行一个函数。一直在尝试,用不同的方法,但仍然徒劳无功 我希望我的服务只有在添加了loainterms之后才发布newLoan(这是一个API调用),但不会等待执行下一个函数而没有上一个函数的响应 在发布这个问题之前,我已经尝试了不同的方法,尽管我将代码放在函数的subscribe方法中。但我还是没有按照我想要的方式去做。 问题是我有一个产品列表,我必须对每个产品执行一个网络操作,然后执行另一个功能,但它只等待第一个产品,之后我不等待并执行下一个功能。 这是我的

我试图在返回前一个函数的成功响应后执行一个函数。一直在尝试,用不同的方法,但仍然徒劳无功

我希望我的服务只有在添加了
loainterms
之后才发布
newLoan
(这是一个API调用),但不会等待执行下一个函数而没有上一个函数的响应

在发布这个问题之前,我已经尝试了不同的方法,尽管我将代码放在函数的
subscribe
方法中。但我还是没有按照我想要的方式去做。 问题是我有一个产品列表,我必须对每个产品执行一个网络操作,然后执行另一个功能,但它只等待第一个产品,之后我不等待并执行下一个功能。 这是我的密码

{
    this.newLoanForm.value.invoiceDate = this.loanDate.format();
    document.getElementById('submitButton').style.display = 'none';

   
    // Adding number of months against give loan term ID
    let loanProducts = this.loanProductForm.value.products;
    let loanTerm;

    loanProducts.forEach(product => {
      this.loanTermService.getLoanTerm(product.loanTermId).subscribe((response: any) => {
        // console.log('Number of months: ', response.numberOfMonths)
        loanTerm = response.numberOfMonths;
        product.installmentStartDate = this.installmentStartDate.format();
        product.monthlyInstallment = product.total / loanTerm;

        // I want this function to executed after all the products have been completed their network activity, but it only waits for just 1st product, after that it executes the below code. how do I make it wait for all products.
        this.loanService.postLoan(this.newLoanForm.value).subscribe((response: any) => {

          console.log('Loan added successfully: ', response);
          PNotify.success({
            title: 'Loan added Successfully',
            text: 'Redirecting to list page',
            minHeight: '75px'
          })
          document.getElementById('submitButton').style.display = 'initial';
          this.router.navigate(['searchLoan']);

        }, (error) => {
          console.log('Error occured while adding loan: ', error);
          PNotify.error({
            title: 'Error occured while adding loan',
            text: 'Failed to add new loan',
            minHeight: '75px'
          })
          document.getElementById('submitButton').style.display = 'initial';
        })

      }, error => {
        console.log('Error while retrieving loanTermId: ', error);
      });
    });


    this.newLoanForm.value.loanProducts = loanProducts;
    console.log('Loan Products: ', this.loanProductForm.value);

下面是我如何用promise和
async
wait

async calculateInstallments() {
    // Adding number of months against give loan term ID
    this.loanProducts = this.loanProductForm.value.products;
    // let loanTerm;

    this.loanProducts.forEach(async product => {
      console.log('Call to get loanTerms: ', await this.loanTermService.getLoanTermById(product.loanTermId));
      let response: any = await this.loanTermService.getLoanTermById(product.loanTermId);
      await this.loanProductService.getLoanProductByLoanId(product.loanTermId).then(() => {
        let loanTerm = response.numberOfMonths;
        console.log('loanTerms', loanTerm);
        product.installmentStartDate = this.installmentStartDate.format();
        product.monthlyInstallment = product.total / loanTerm;
      });

    });
  }
// putting the function I want to execute after the response of previous in the `then` method

    await this.calculateInstallments().then(() => {

      this.newLoanForm.value.loanProducts = this.loanProducts;
      // Posting loan after the response of loanTerms Service
      this.loanService.postLoan(this.newLoanForm.value).subscribe((response: any) => {

        console.log('Loan added successfully: ', response);
        PNotify.success({
          title: 'Loan added Successfully',
          text: 'Redirecting to list page',
          minHeight: '75px'
        });
        document.getElementById('submitButton').style.display = 'initial';
        this.router.navigate(['searchLoan']);

      }, (error) => {
        console.log('Error occured while adding loan: ', error);
        PNotify.error({
          title: 'Error occured while adding loan',
          text: 'Failed to add new loan',
          minHeight: '75px'
        });
        document.getElementById('submitButton').style.display = 'initial';
      });


    });
但不幸的是,它没有起作用。

我今天也遇到了几乎相同的问题。也许你仍然需要一个解决方案,否则就把它看作另一种方式

如果您使用
async
wait
daisy-chain
样式搭配
newpromise
,您不介意。从
async
framework的3.x版开始,如果不使用
callback
,您将能够使用惊人的迭代函数(不知道是否全部)作为承诺

这是一个简单的示例,说明如何使用
eachOf
函数异步执行任务

const async=require('async');
让项目=[
{姓:“约翰”,姓“多伊”},
{姓:“简”,姓“多伊”},
{名字:'我',名字:'我和我'}
];
async.eachOf(项,(项,索引,回调)=>{
//在这里,您可以从items数组中以item的形式查询具有vaulues的db
log('这是项:',项);
新承诺(解决=>{
设置超时(()=>{
决心(正确);
}, 500);
})
。然后(结果=>{
//也许你需要做点别的
log('这是结果:',结果);
回调();
});
})
.然后(()=>{
//继续使用菊花链
console.log(“所有项目已更新”);
});

我希望您可以使用此设置,或者这是一个重新构造此设置的灵感,并以另一种方便的方式使用
async
wait

这是否回答了您的问题?我已经尝试过承诺,但没有成功。您的
async/await
代码片段清楚地表明您没有阅读我上面链接的问题。不能使用这样的forEach使异步函数等待每个产品处理完毕。使用普通循环。在这种情况下,普通循环可以正常工作吗?
.forEach()
在数组的每个元素上立即调用异步函数,而无需等待上一个函数完成。如果对循环使用常规的
,则可以在循环继续到下一次迭代之前等待每个元素的处理