【发布时间】:2018-04-17 10:50:20
【问题描述】:
我正在尝试使用 Stripe Node 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!");
});
}
【问题讨论】:
-
这段代码现在会发生什么...
stripe.customers.list是否偶然返回了一个承诺? -
@JaromandaX 是的
-
promise 解析为什么值?与回调中的
res相同? -
@user4815162342 如果它确实返回了一个承诺,那么 a) 你为什么不
return你的函数中的承诺和 b) 你为什么仍然传递一个 nodeback?
标签: javascript node.js promise async-await ecmascript-2017