2016-12-03 16 views
0

サーバーからデータを取得し、要求後に関数を呼び出す非同期要求を実行しています。私の質問は、要求が完了し、processRecords()が実行される前にロードされたすべてのデータを確実にする方法です。関数を実行する前に非同期要求が完了したことを確認する方法

ありがとうございます。

function getRecords() { 
    var ids = Server.getIds(); 
    var allTheRecords = []; 

    ids.forEach(function(recordId) { 
    Server.getRecord(recordId, function (error, data) { 
     if(error) { 
     console.log(error); 
     } else { 
     allTheRecords.push(data); 
     }; 
    }); 
    }); 

    processRecords(allTheRecords); 
} 

答えて

0

Promise apiを使用すると、非同期処理を実行できます。

Promise.allを使用すると、processRecords関数を呼び出す前に解決する必要がある約束事を与えることができます。

コード内の別の場所で使用できるgetRecord関数を使用すると、コードを再利用できるようになりました。

もしあなたがそれを制御しても、サーバーから複数のレコードを取得する機能を追加する方法を考えるべきでしょう。ネットワーク要求を1つだけ行うことができれば、たくさんのネットワーク要求を発したくはありません。

// Server mock of the api you have shown 
 
const Server = { 
 
    getRecord(id, callback) { 
 
    console.log('getRecord', id) 
 
    callback(null, {id}) 
 
    }, 
 
    getIds() { 
 
    return [1, 2, 3] 
 
    } 
 
} 
 

 
function getRecords (ids, processRecords) { 
 
    console.log('getRecords', ids.join()) 
 
    // mapping the array of id's will convert them to an 
 
    // array of Promises by calling getRecord with the id 
 
    Promise.all(ids.map(getRecord)) 
 
    // then is called once all the promises are resolved 
 
    .then(processRecords) 
 
    // this will be called if the reject function of any 
 
    // promise is called 
 
    .catch(console.error.bind(console)) 
 
} 
 

 
function getRecord(recordId) { 
 
    // this function returns a Promise that wraps your 
 
    // server call 
 
    return new Promise((resolve, reject) => { 
 
    Server.getRecord(recordId, function (error, data) { 
 
     if(error) { 
 
     reject(error) 
 
     } else { 
 
     resolve(data) 
 
     } 
 
    }) 
 
    }) 
 
} 
 

 
getRecords(Server.getIds(), function(records) { 
 
console.log('resolved all promises') 
 
console.log(records) 
 
})

+0

フィードバックに感謝します。私は理解しているかどうかわからない:/この練習の目的のために、私はこのファイルにアクセスすることができませんserver.jsファイル内のgetRecord関数にアクセスすることができません。私は渡すことについて約束を読んだが、まだ何も実装していない。 –

+0

@LukeAveilそれが何をしているのかを理解する最良の方法は、devtoolsにブレークポイントを入れて、実行するコードをステップ実行することです。あなたのサーバapiのモックで少し修正しましたので、スニペットで動作します – synthet1c

0

どのように非同期リクエストを実行していますか? AJAXリクエストの場合、APIはコールの結果に基づいてコールバックを提供します。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

+0

リクエストは '' 'Server.getRecord()' ''によって実行されます。残念ながらAJAXリクエストではありません...これが私が少し苦労している理由です。 –

+0

「サーバー」はどこから来たのですか?どのAPIを使用していますか。 –

関連する問題