【问题标题】:How to send several requests in turn in a loop js如何在一个循环js中依次发送多个请求
【发布时间】:2020-01-01 02:05:01
【问题描述】:

我需要在循环中的上一个请求结束后每次发送一个请求。但我不能通过异步/等待来做到这一点。请帮忙。

    genQuote = () => {
    let quotes = [{quote: 1},{quote: 2}...{quote: n}]

    quotes.map(async (simple,i) => {
      await this.sendSimple(simple)
    }).then(()=>{console.log('Done ' + i)}))
  }

  sendSimple = (simple) => {
    request('rest/api', {
      method: 'POST',,
      body: JSON.stringify(simple)
    })
  }

【问题讨论】:

  • return this.sendSimple(simple);return request('rest/api', ...) 你的函数需要返回承诺等待等待做任何有趣的事情。
  • 尽量不要将 async/await 与 .then().catch() 混合使用

标签: javascript promise async-await fetch


【解决方案1】:

如果您希望它在运行下一次迭代之前等待,您可以使用for...of

   async function genQuote() {
    let quotes = [{quote: 1},{quote: 2}...{quote: n}];

     for (let quote of quotes) {
      await this.sendSimple(simple);
    }

    console.log('All Done');

  }

但您还需要 sendSimple 函数返回 Promise

【讨论】:

    【解决方案2】:

    sendSimple 必须返回一个 promise 让你使用 async, await。您也不能在这样的地图中使用 await 。除非您想使用 Promise.all 同时触发所有这些,否则只需使用循环即可。像这样的东西应该可以解决问题:

        async genQuote = () => {
          let quotes = [{ quote: 1 }, { quote: 2 }...{ quote: n }]
          for (let i = 0; i < quotes.length; i++){
            await this.sendSimple(simple);
            console.log('Done ' + i)
          }
        }
    
    
    async sendSimple = (simple) => {
       new Promise((resolve, reject) => {
            request('rest/api', {
                method: 'POST',
                body: JSON.stringify(simple)
            })
                .then(resolve)
                .catch(err => reject(err))
        })
    }
    

    【讨论】:

    • 应该是不带括号的 .then(resolve) 以防调用代码想要对结果做些什么。
    • 另外,你应该删除 sendSimple 中使用的 async/await,它们不是必需的。
    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多