ノード環境でcronジョブで実行するプロセスを作成しています。これらのネストされた約束はなぜ機能しないのですか?
プロセスは、2つの外部サービスから2つのユーザーリストを取得し、ファイルに書き込み、比較を行います。
ユーザーのソースの1つはDiscourseフォーラムです。残念ながら、フルユーザーリストを取得するには、複数のtrust_level
リストを取得して連結する必要があります。
私はさまざまなネストされた約束とPromise.all
を使用してこれを構成しました。しかし、以下の関数は、とdatabaseList.json
の存在する前に、そのthen
コールバックを呼び出すことが早すぎます...私はここで間違っていますか?
import superagent from 'superagent'
import { writeFileSync } from 'fs'
export default function fetchData() {
const process = []
const databaseFetch = new Promise((resolve, reject) => {
superagent.get('https://our-api.com/api/1/databases/our-db/collections/users')
.end((error, response) => {
if (error) {
reject(error)
} else {
writeFileSync('temp/databaseList.json', JSON.stringify(response.body))
resolve()
}
})
})
const forumFetch = new Promise((resolve, reject) => {
// For reference, see https://meta.discourse.org/t/how-do-i-get-a-list-of-all-users-from-the-api/24261/8
// We have to do this because of the way the discourse API is built
const discourseApiList = [
'trust_level_0',
'trust_level_1',
'trust_level_2',
'trust_level_3',
'trust_level_4',
]
let forumList = []
const discoursePromises = discourseApiList.map((trustLevel) => {
return new Promise((resolveInner, rejectInner) => {
superagent.get(`https://our-website.com/forum/groups/${trustLevel}/members.json`)
.end((error, response) => {
if (error) {
rejectInner(error)
reject()
} else {
forumList = forumList.concat(response.body.members)
resolveInner()
}
})
})
})
Promise.all(discoursePromises).then(() => {
writeFileSync('temp/forumList.json', JSON.stringify(forumList))
resolve()
})
})
process.push(databaseFetch)
process.push(forumFetch)
return Promise.all(process)
}
最後の行に戻り値がありません。 – mikeapr4
@ mikeapr4いいえ、違いはありません –
@ジョンドー。あまりにも早く呼ばれていますか? –