javascript - 避免回调地狱和组织 Node.js 代码
问题描述
我正在尝试组织我的代码并想为每个 .then() 创建单独的函数,有些我无法做到,而且我的代码中断
请帮助我如何使事情正常进行
module.exports = function () {
return new Promise((resolve, reject) => {
try {
const settings = blob();
var {
someObject
} = JSON.parse(requestBody);
var var1,var2,var3
let somePromises = [];
someObject.forEach((p) => {
p.somepro = 'anything';
});
Promise.all(somePromises)
.then((res) => {
//replace cart item info
res.forEach((r) => {
someObject.forEach((so) => {
so.info = ''
});
});
});
return require('/file1')(); // api call 1
})
.then((res) => {
var2 = resp.something // local variable create above var2
return require('/file2')(); // api call 2
})
.then((res) => {
var3 = resp.something // local variable create above var3
return require('/file2')(); // api call 3
})
.then((r) => {
// some other maniuplation
})
.then(() => {
// some calulation based on above responses and local variable
// assigned
resolve({
someObject,
var1,
var2
});
});
} catch (e) {
reject(e);
}
});
};
我正在尝试使代码组织并为每个承诺创建单独的功能,但不会感到困惑和困惑我如何以有组织和最佳实践的方式创建此流程
解决方案
首先不要resolve
对象,它不是那么安全,因为then
如果它是一个函数,Promise 正在使用该属性。
像这样返回的对象在console.log
ing ...
但是让我们假设在您的承诺解决您的对象之前,某些方法会then
在您的对象中添加/替换一个方法,然后您将对这些承诺进行一些调试。
我正在尝试组织我的代码,并想为每个 .then() 创建单独的函数
我创建了一个自定义方法,它按顺序传递 Promise.all 值.then
。
您的要求是为每个.then
. 只需复制粘贴useIfFor
方法并根据需要重命名/更改它。
PS:你的代码中的一些块仍然存在......它们是无害的。
console.clear();
let module = {};
module.exports = () => {
return new Promise((resolve, reject) => {
const settings = {}; //blob();
var {
someObject
} = JSON.parse(typeof requestBody !== 'undefined' ? requestBody : '[]');
let somePromises = [
Promise.resolve('some text'),
Promise.resolve(100),
Promise.resolve(10000),
];
// var var1, var2, var3
let stackVariables = [];
// It passes the first value from Promise.all to the first 'then'
// the 2nd value to the 2nd `then`
// the 3rd value to the 3rd `then`
// ...
// the N-th value to the N-th `then`
const useIfFor = (someStringOrNumber) => {
return (res) => {
// We'll use the first value of `res` and pass the rest of the values to the next `then`
let [promiseValue, ...restOfTheValues] = res;
// START HERE - To add your logic - `promiseValue` is your old 'res'
console.log('Current `then` value:', promiseValue, '| Label:', someStringOrNumber);
if (someStringOrNumber === 'my-first-then') {
promiseValue = 'THIS VALUE IS MODIFIED';
stackVariables.push(promiseValue); // first value from Promise.all
} else if (someStringOrNumber === 'my-second-then') {
stackVariables.push(promiseValue); // second value from Promise.all
} else if (someStringOrNumber === 'my-third-then') {
stackVariables.push(promiseValue); // third value from Promise.all
} else {
// You can end it with resolve anywhere
//resolve(stackVariables);
}
// END HERE
if (typeof promiseValue === 'undefined') {
// You reached the end, no more values.
resolve(stackVariables);
}
// Passing the remaining values to the next `then`
return restOfTheValues;
}
}
Promise.all(somePromises)
.then(useIfFor('my-first-then'))
.then(useIfFor('my-second-then'))
.then(useIfFor('my-third-then'))
.then(useIfFor('done')) // <- here is the resolve because there isn't the 4th promise, therefore, no values
.catch((err) => {
reject(err);
})
});
};
(module.exports)()
.then(res => {
console.log('res', res);
}).catch(console.error);
推荐阅读
- java - 错误消息“找到可能不是 UTF-8 编码的字符”是什么意思?
- gradle - Java Home 不断恢复到 JRE,但我需要 JDK
- assembly - 需要用汇编计算二进制中 1 的数量
- amazon-ec2 - 将 AWS EBS 挂载到 CoreOS
- javascript - 如果选择了“所有年份”选项,则共享相同的 php 函数
- vue.js - 在VUE中将动态对象值传递给Modal Popup打开错误的ID值
- sql - SELECT 在任何地方返回多于一行的 sql
- javascript - 将点击功能更改为仅播放
- sql - 我需要通过存储适当的 CityId 而不是 CityName 将数据从一个旧表迁移到新表
- opencv - 使用 V4L 进行 OpenCv 捕获