我是 Node js新手,我正在尝试创建一个返回对象列表的rest方法,一切都很好,直到我想发送响应,逻辑执行如下操作:
- 查找对象
- 初始化对象
- 将对象插入列表
- 发送包含对象的列表
发生的情况是,第 3 点发生在第 4 点之后,我得到了一个空列表,经过研究,我发现这是由于 Node 的异步性质,我尝试使用 Promise 重写代码,但我找不到一个 promise 调用另一个 promise 的示例
第一个版本
app.get('/initDevices', (req, res) => {
console.log('init devices.');
cameras = [];
onvif.startProbe().then((device_info_list) => {
let requests = device_info_list.map((info) => {
processDevice(info)
});
Promise.all(requests).then(() => {
console.log('all done ');
res.json(cameras);
});
}).catch((error) => {
res.json('nothing');
});
});
function processDevice(info) {
return new Promise((resolve, reject) => {
console.log("step 1");
let device = new onvif.OnvifDevice();
console.log("step 2");
device.init().then((devinfo) => {
console.log("step 3");
cameras.push(devinfo);
console.log("cameras: " + cameras.length);
resolve("done");
}).catch((error) => {
reject("It broke");
});
});
}
输出
init devices.
step 1
step 2
//response goes to the user with empty array []
step 3 //push happens
第二次尝试(有 promise )
function processDevice(info) {
return new Promise((resolve) => {
console.log("step 1");
let device = new onvif.OnvifDevice();
console.log("step 2");
resolve(device);
}).then((device) => {
console.log("step 3");
return device.init();
}).then((device) => {
console.log("step 4");
return cameras.push(device);
});
}
输出
init devices.
step 1
step 2
step 3
//response goes to the user with empty array []
step 4 //push happens
我认为这一行返回 device.init(); promise 完成但我不知道为什么。
有人可以帮助我理解为什么链条不能按预期工作吗? 我做错了什么?
顺便说一句,我遵循的示例是 here但这些操作只是一些添加,不会调用其他 promise
编辑:我找到了更好的方法来实现这一目标
function processDevice(info) {
let device = new onvif.OnvifDevice();
return device.init().then(() => {
console.log("init done");
cameras.push(camObj);
});
}
由于 promise 已经被使用,因此没有必要将其包装在另一个 promise 中
最佳答案
您的 requests
变量未定义 - 您必须返回 map 内的 processDevice(info)
,如下所示:
let requests = device_info_list.map((info) => {
return processDevice(info)
});
关于javascript - 如何在 Node js 中链接一个调用另一个 Promise 的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434116/