【问题标题】:How to use promises to wait for async API calls如何使用 Promise 等待异步 API 调用
【发布时间】:2017-02-20 21:50:02
【问题描述】:

我正在创建一个 API,当 GET 时,对 News API 进行一系列调用,新闻文章标题被提取成一个巨大的字符串,并且该字符串被处理成一个对象以传递到前面的 wordcloud -结尾。到目前为止,我已经能够使用下划线的_.after 和request-promise 让我的应用程序等到所有API 调用完成后再调用processWordBank(),它将巨大的字符串清理成一个对象。但是,一旦调用processWordBank(),我就不明白程序的流程在哪里。理想情况下,processWordBank() 将 obj 返回到路由器中的 cloudObj,以便可以将 obj 传递给res.json() 并作为响应吐出。我相信我对_.after 的使用让我处于一个奇怪的境地,但这是我能够在进行下一个所需操作之前完成异步调用的唯一方法。有什么建议吗?

(我试图省略所有不必要的代码,但如果这还不够,请告诉我)

// includes...
var sourceString = ""
// router
export default ({ config }) => {
  let news = Router()
  news.get('/', function(req, res){
    var cloudObj = getSources()
        res.json({ cloudObj })
  })
  return news
}

// create list of words (sourceString) by pulling news data from various sources
function getSources() {
    return getNewsApi()

}
// NEWS API
// GET top 10 news article titles from News API (news sources are determined by the values of newsApiSource array)
function getNewsApi() {
  var finished = _.after(newsApiSource.length, processWordBank)
  for(var i = 0; i < newsApiSource.length; i++) {
    let options = {
      uri: 'https://newsapi.org/v1/articles?source=' + newsApiSource[i] + '&sortBy=' + rank + '&apiKey=' + apiKey,
      json: true
    }
    rp(options)
    .then(function (res) {
      let articles = res.articles // grab article objects from the response
      let articleTitles = " " + _.pluck(articles, 'title') // extract title of each news article
      sourceString += " " + articleTitles // add all titles to the word bank
      finished() // this async task has finished
    })
    .catch(function (err) {
      console.log(err)
    })
    }
}

// analyse word bank for patterns/trends
function processWordBank(){
  var sourceArray = refineSource(sourceString)
  sourceArray = combineCommon(sourceArray)
  sourceArray = getWordFreq(sourceArray)
  var obj = sortToObject(sourceArray[0], sourceArray[1])
  console.log(obj)
  return obj
}

【问题讨论】:

  • 而不是finished() 尝试实际返回 一些东西......也许return finished() - 但是你会希望getNewsApi 也返回一些东西

标签: javascript node.js promise


【解决方案1】:

异步流程中的一个大问题是您使用共享变量sourceString 来处理结果。当您多次调用getNewsApi() 时,您的结果是不可预测的并且不会总是相同的,因为没有预定义的异步调用执行顺序。不仅如此,而且您永远不会重置它,因此所有后续调用也将包括先前调用的结果。避免在异步调用中修改共享变量,而是直接使用结果。

我已经能够使用下划线的_.after 和 request-promise 让我的应用等到所有 API 调用完成后再调用 processWordBank()

虽然可以使用_.after,但这可以通过promise 很好地完成,并且由于您已经在使用promise 来处理您的请求,因此只需从它们那里收集结果。因此,因为您想等到所有 API 调用完成,您可以使用 Promise.all ,它返回一个 promise,一旦所有 promise 的值都得到满足,该 promise 将解析为一个数组。让我们看一个非常简单的例子,看看Promise.all 是如何工作的:

// Promise.resolve() creates a promise that is fulfilled with the given value
const p1 = Promise.resolve('a promise')
// A promise that completes after 1 second
const p2 = new Promise(resolve => setTimeout(() => resolve('after 1 second'), 1000))
const p3 = Promise.resolve('hello').then(s => s + ' world')
const promises = [p1, p2, p3]

console.log('Waiting for all promises')
Promise.all(promises).then(results => console.log('All promises finished', results))
console.log('Promise.all does not block execution')

现在我们可以修改getNewsApi() 以使用Promise.all。提供给Promise.all 的承诺数组是您在循环中执行的所有 API 请求。这将使用Array.protoype.map 创建。而且我们也可以直接使用数组,而不是从_.pluck返回的数组中创建一个字符串,所以你不需要在最后将字符串解析回一个数组。

function getNewsApi() {
  // Each element is a request promise
  const apiCalls = newsApiSource.map(function (source) {
    let options = {
      uri: 'https://newsapi.org/v1/articles?source=' + source + '&sortBy=' + rank + '&apiKey=' + apiKey,
      json: true
    }
    return rp(options)
      .then(function (res) {
        let articles = res.articles
        let articleTitles = _.pluck(articles, 'title')
        // The promise is fulfilled with the articleTitles
        return articleTitles
      })
      .catch(function (err) {
        console.log(err)
      })
  })
  // Return the promise that is fulfilled with all request values
  return Promise.all(apiCalls)
}

然后我们需要使用路由器中的值。我们知道从getNewsApi() 返回的promise 满足所有请求的数组,这些请求本身返回一个文章数组。那是一个二维数组,但大概你会想要一个包含 processWordBank() 函数的所有文章的一维数组,所以我们可以先将其展平。

export default ({ config }) => {
  let news = Router()
  new.get('/', (req, res) => {
    const cloudObj = getSources()
    cloudObj.then(function (apiResponses) {
      // Flatten the array
      // From: [['source1article1', 'source1article2'], ['source2article1'], ...]
      // To: ['source1article1', 'source1article2', 'source2article1', ...]
      const articles = [].concat.apply([], apiResponses)
      // Pass the articles as parameter
      const processedArticles = processWordBank(articles)
      // Respond with the processed object
      res.json({ processedArticles })
    })
  })
}

最后processWordBank() 需要更改为使用输入参数而不是使用共享变量。 refineSource 不再需要,因为您已经在传递一个数组(除非您在其中进行一些其他修改)。

function processWordBank(articles) {
  let sourceArray = combineCommon(articles)
  sourceArray = getWordFreq(sourceArray)
  var obj = sortToObject(sourceArray[0], sourceArray[1])
  console.log(obj)
  return obj
}

作为奖励,路由器和getNewsApi() 可以用一些ES6 features 清理(没有上面sn-ps 中的cmets):

export default ({ config }) => {
  const news = Router()
  new.get('/', (req, res) => {
    getSources().then(apiResponses => {
      const articles = [].concat(...apiResponses)
      const processedArticles = processWordBank(articles)
      res.json({ processedArticles })
    })
  })
}

function getNewsApi() {
  const apiCalls = newsApiSource.map(source => {
    const options = {
      uri: `https://newsapi.org/v1/articles?source=${source}&sortBy=${rank}&apiKey=${apiKey}`,
      json: true
    }
    return rp(options)
      .then(res => _.pluck(res.articles, 'title'))
      .catch(err => console.log(err))
  })
  return Promise.all(apiCalls)
}

【讨论】:

  • 老兄,这非常有帮助。使用 API 调用的 Promise 帮助我解决了问题。谢谢!
猜你喜欢
  • 2018-03-31
  • 2021-03-17
  • 2021-05-12
  • 2020-03-04
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多