javascript - Javascript - 如何从异步每个函数返回值?

我知道这是常见的问题,我查看了一些教程和文档,但是还没理解透彻。

下面是我的控制器函数:


exports.appDetail = function (req, res) {


 appRepo.findWithId(req.params.id, (err, myApp) => {


 if (err) {


 console.log(err)


 }


 getDeviceData(myApp.devices, (err, myDeviceData) => {


 if (err) console.log(err)


 console.log(JSON.stringify(myDeviceData) + ' || myDeviceData')


 // construct object to be returned


 let appsDataObject = {


 name: myApp.name,


 user_id: myApp.user_id,


 devices: myDeviceData,


 permissions: myApp.permissions


 }


 return res.status(200).send(appsDataObject)


 })


 })


}



// write async function here


const getDeviceData = function (devices, callback) {


 let devicesDataArray = []


 async.each(devices, function (device, cb) {


 deviceRepo.findById(new ObjectID(device), (err, myDevice) => {


 if (err) {


 cb(err)


 }


 // get device data, push to devices array


 let deviceObj = {


 name: myDevice.name,


 version: myDevice.version


 }


 devicesDataArray.push(deviceObj)


 console.log(JSON.stringify(devicesDataArray) + ' || devicesDataAray after obj push')


 })


 cb(null, devicesDataArray)


 }, function (err) {


 // if any of the file processing produced an error, err would equal that error


 if (err) console.log(err)


 })


 callback(null, devicesDataArray)


}



我最初用循环和回调来实现,但是我认为做不到的(但我不确定),

我不理解这些异步函数是如何工作的,谢谢

时间:

我们可以使用Promise

返回Promise对象,我们将在那里执行异步代码。


const someFuncThatTakesTime = () => {


 // Here is our ASYNC 


 return new Promise((resolve, reject) => {


 // In here we are synchronous again. 


 const myArray = []; 


 for(x = 0; x < 10; x++) {


 myArray.push(x);


 }



 // Here is the callback 


 setTimeout(() => resolve(myArray), 3000); 


 });


};



someFuncThatTakesTime().then(array => console.log(array));

首先,避免使用回调,因为它将使你的代码无法被理解,也可以使用async,它是内建的javascript方法。 问题的原因是,你执行了async.each函数,而没有等待它响应内容,


 exports.appDetail = function async(req, res) {


 try {


 const myApp = await appRepo.findWithId(req.params.id)


 const myDeviceData = await getDeviceData(myApp.device)


 console.log(JSON.stringify(myDeviceData) + ' || myDeviceData')


 // construct object to be returned


 let appsDataObject = {


 name: myApp.name,


 user_id: myApp.user_id,


 devices: myDeviceData,


 permissions: myApp.permissions


 }


 return res.status(200).send(appsDataObject)


 } catch (err) {


 console.log(err)


 }



}



// write async function here


const getDeviceData = function async(devices) {


 let devicesDataArrayPromises = devices.map(async(device)=>{


 const myDevice= await deviceRepo.findById(new ObjectID(device))


 let deviceObj = {


 name: myDevice.name,


 version: myDevice.version


 }


 return deviceObj


 })


 const devicesDataArray = await Promise.all(devicesDataArrayPromises)


 console.log(JSON.stringify(devicesDataArray) + ' || devicesDataAray after obj push')


return devicesDataArray


}



...