ES6承诺:等待轮询完成设置var

时间:2018-04-02 03:25:55

标签: javascript ecmascript-6 es6-promise

我正在调用这样的轮询函数:

PollServer.getData(id)

这个过程大约需要10秒,并且有30秒的超时时间。如何分配一个等待超时或成功响应的变量(这是一个数组)?

这使它立即设置值而不是等待进程:

var response = PollServer.getData(id)

这样做:

fetch(PollServer.getData(id))
  .then(function(response) {
    console.log(`Final: ${response}`)
}).catch(function(error) {
  console.log(`Super error: ${error}`)
})

我错过了什么?

这是PollServer班级:

export class PollServer {
  static getData(id) {
    const token = process.env.SERVER_TOKEN,
          endpoint = `/documents/${id}`,
          request = `${endpoint}/request?token=${token}`,
          result = `${endpoint}/result?token=${token}`

    fetch(request, { method: 'get' })
      .then(function(response) {
        PollServer.poll(function() {
          return fetch(result, { method: 'get' })
        }, 30000, 500)
      .then(function(response) {
        console.log(`Finished: ${JSON.stringify(response)}`)
        return [response.low_url, response.high_url]
      })
    }).catch(function(error) {
      console.log(`Error: ${error}`)
    })
  }

  static poll(fn, timeout, interval) {
    var endTime = Number(new Date()) + (timeout || 2000)
    interval = interval || 100

    var checkCondition = function(resolve, reject) {
      var fetchCall = fn()
      fetchCall.then(function(response) {
        return response.json()
      }).then(function(response) {
        if (JSON.stringify(response.created) == 'true') {
          resolve(response)
        } else if (Number(new Date()) < endTime) {
          setTimeout(checkCondition, interval, resolve, reject)
        } else {
          reject(new Error(`Timeout: ${fn} with ${arguments}`))
        }
      })
    }
    return new Promise(checkCondition)
  }
}

1 个答案:

答案 0 :(得分:0)

所以根据this帖子,我解决了我的问题,主要是返回Promise,la:

static getData(id) {
    const token = process.env.SERVER_TOKEN,
          endpoint = `/documents/${id}`,
          request = `${endpoint}/request?token=${token}`,
          result = `${endpoint}/result?token=${token}`

    return new Promise(function(resolve, reject) { // see here for what to do
      fetch(request, { method: 'get' })
        .then(function(response) {
          PollServer.poll(function() {
            return fetch(result, { method: 'get' })
          }, 30000, 500)
        .then(function(response) {
          resolve(response) // and resolve it here
        })
      }).catch(function(error) {
        reject(new Error(`Error: ${error}`))
      })
    })
}