[英]Javascript get callback from function within map
I have been struggling with this for quite sometime and haven't been able to find a good solution for this problem. 我已经为此苦苦挣扎了很长时间,但一直没有找到解决这个问题的好方法。
I have an array which I map through an imported function that has a call back. 我有一个数组,该数组通过具有回调的导入函数进行映射。 I want to get the data(JSON) from the callback, manipulate it, output it and run it through another function.
我想从回调中获取数据(JSON),对其进行操作,输出并通过另一个函数运行它。
Because the node_module qbo.getBill function has a callback, I don't think I can run promise or async\\await, well I haven't had any success doing so as soon as I add the getBill function. 因为node_module qbo.getBill函数具有回调,所以我认为我无法运行promise或async \\ await,所以一旦添加getBill函数,我就没有获得成功。
Here is my code/what I am trying to do: 这是我的代码/我正在尝试做的事情:
var QuickBooks = require('node-quickbooks') var qbo = new QuickBooks(...) let BillIds = [....] let newArray =[] let mapData = BillIds.map(val => { qbo.getBill(val, function (err, Billid) { newArray.push = { id: Billid.Id, balance: Billid.Balance } }) }) DoAThingWithAsyncronousData(newArray)
For the life of me I can't get any action to wait on the the asynchronous data before completing the next step, where am I going wrong? 为了我的一生,在完成下一步之前,我无法采取任何措施等待异步数据,我在哪里出错呢?
Sure you can use Promise.all, you just need to put a promise around getBill
's callback: 确保可以使用Promise.all,您只需要在
getBill
的回调周围getBill
承诺getBill
:
const newArray = await Promise.all(
BillIds.map(val => new Promise((resolve, reject) => {
qbo.getBill(val, (err, Billid) => {
const billObj = {
id: Billid.Id,
balance: Billid.Balance
}
resolve(billObj)
});
}))
);
DoAThingWithAsyncronousData(newArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.