2017-11-05 1 views
0

ストライプノードAPIを使用しているすべての顧客のリストをコンパイルしようとしています。一度に100人の顧客を継続的に取得する必要があります。非同期待機を使用するためにAPI呼び出し内でPromiseを使用する必要があると私は信じていますが、私の人生にとってはどこに置くのか分かりません。この要点を一般に使用することを願って、私はそれを正しく、感謝したい。すべてのストライプ顧客を非同期で取得することをお待ちしております

getAllCustomers() 

function getMoreCustomers(customers, offset, moreCustomers, limit) { 
    if (moreCustomers) { 
    stripe.customers.list({limit, offset}, 
     (err, res) => { 
     offset += res.data.length 
     moreCustomers = res.has_more 
     customers.push(res.data) 
     return getMoreCustomers(customers, offset, moreCustomers, limit) 
     } 
    ) 
    } 
    return customers 
} 

async function getAllCustomers() { 
    const customers = await getMoreCustomers([], 0, true, 100) 
    const content = JSON.stringify(customers) 
    fs.writeFile("/data/stripe-customers.json", content, 'utf8', function (err) { 
     if (err) { 
      return console.log(err); 
     } 
     console.log("The file was saved!"); 
    }); 
} 
+0

のように固定することができる... '偶然約束を返しstripe.customers.list'ん? –

+0

@JaromandaXはいそれは – user4815162342

+0

約束どおりに解決しますか?コールバックの 'res'と同じですか? –

答えて

0

stripe.customers.list({limit, offset}).then(res => ...)resstripe.customers.list({limit, offset}, (err, res)の "コールバック" バージョンでresと同じである場合 - あなたはおそらくあなたのコードを書き換えることができよう

const getMoreCustomers = limit => { 
    const getThem = offset => stripe.customers.list({limit, offset}) 
    .then(res => res.has_more ? 
     getThem(offset + res.data.length).then(result => res.data.concat(...result)) : 
     res.data 
    ); 
    return getThem(0); 
}; 

async function getAllCustomers() { 
    const customers = await getMoreCustomers(100); 
    const content = JSON.stringify(customers); 
    fs.writeFile("/data/stripe-customers.json", content, 'utf8', function (err) { 
     if (err) { 
      return console.log(err); 
     } 
     console.log("The file was saved!"); 
    }); 
} 
0

追加Jaromanda Xさんへ答え、顧客のAPIにはoffsetオプションがないようですが、starting_afterhttps://stripe.com/docs/api/node#list_customers

ので、getMoreCustomersは、このコードで今何が起こるか

const getMoreCustomers = starting_after => { 
    const getThem = starting_after => stripe.customers.list({limit: 100, starting_after: starting_after}) 
    .then(res => res.has_more ? 
     getThem(res.data[res.data.length - 1]).then(result => res.data.concat(...result)) : 
     res.data 
); 
    return getThem(starting_after); 
}; 

async function getAllCustomers() { 
    const customers = await getMoreCustomers(null); 
    const content = JSON.stringify(customers); 
    fs.writeFile("/data/stripe-customers.json", content, 'utf8', function (err) { 
    if (err) { 
     return console.log(err); 
    } 
    console.log("The file was saved!"); 
    }); 
} 
関連する問題