2017-12-22 13 views
0

私は、ユーザー提供の用語を検索し、結果の配列を返し、各結果の非同期リクエストを発生させ、これらの第2バッチのリクエスト。最終結果だけでなく進捗状況をAPIに報告したいと思います。ですから、私が次のような要求をすると、そういう更新を得るべきです。nodejs async /ネストされたAPIの進行を待ちます

$ curl 'http://server/?q=foobar' 
searching for ${q}… 
found 76… now getting images… 
found 30 images… done 
{ 
    result 
} 

関連するコードのほとんどが以下に示されています。 Fwiw、私はhapijs私のアプリケーションに使用しています。

let imagesOfRecords = {}; 

const getImages = async function (q) { 

    console.log(`searching for ${q}…`); 
    const uri = `http://remoteserver/?q=${q}`; 
    const {res, payload} = await Wreck.get(uri); 
    const result = JSON.parse(payload.toString()).hits; 
    const numOfFoundRecords = result.total; 

    if (result.total) { 

     console.log(`found ${result.total}… now getting images…`); 
     const foundRecords = result.hits.map(getBuckets); 
     Promise.all(foundRecords).then(function() { 

      console.log(`found ${Object.keys(imagesOfRecords).length} images… done`); 
      reply(imagesOfRecords).headers = res.headers; 
     }).catch(error => { 
      console.log(error) 
     }); 
    } 
    else { 
     console.log('nothing found'); 
     reply(0).headers = res.headers; 
    } 
}; 

const getBuckets = async function(record) { 

    const { res, payload } = await Wreck.get(record.links.self); 
    const bucket = JSON.parse(payload.toString()).links.bucket; 
    await getImageFiles(bucket, record.links.self); 
}; 

const getImageFiles = async function(uri, record) { 

    const { res, payload } = await Wreck.get(uri); 
    const contents = JSON.parse(payload.toString()).contents; 
    imagesOfRecords[record] = contents.map(function(el) { 
     return el.links.self; 
    }); 
}; 

私はこれを実装することができたら、私の次の課題は、上記のAPIを使用するWebアプリで、この進歩的なアップデートを実装することであろう。

答えて

1

バックエンドの要求の各ステップで結果を表示するには、EventEmitterを使用します。これは、各進捗ステップでイベントを発生させます。イベントhereについて読むことができます。
シンプルな実装:あなたはherehereを見つけることができます

const events = require('events'); 
const eventEmitter = new events.EventEmitter(); 

//your request code 
Promise.all(foundRecords).then(function() { 
    console.log(`found ${Object.keys(imagesOfRecords).length} images… done`); 
    eventEmitter.emit('progress'); 
    reply(imagesOfRecords).headers = res.headers; 
}) 

const eventReaction = (e) => { 
    // do something with event, console log for example. 
} 
eventEmitter.on('progress', eventReaction); 

より多くの例。
クライアントにイベントを表示するには、ライブラリsocket.ioを使用します。 socket.ioがどのように働くかについて、かなりわかりやすい説明があると思います。documentation
サーバーやプロセス間でイベントを送信したい場合は、0MQ(ゼロmq)とそのノードの詳細を読むことができます。implementation

+0

これは素晴らしいです。私はその提案を試してみる。私のAPIの消費者に進歩の更新と結果を区別する何らかの方法を与えなければならないので、これは価値があるよりも面倒かもしれないと私は言う。実験がたくさんある。 – punkish

関連する問題