Javascript 使for循环在节点js中按顺序执行任务
尽管我使用了.then(),但ctx.reply没有按顺序运行/ 我怎样才能修好它// 我附上一张图片以便更好地理解Javascript 使for循环在节点js中按顺序执行任务,javascript,node.js,Javascript,Node.js,尽管我使用了.then(),但ctx.reply没有按顺序运行/ 我怎样才能修好它// 我附上一张图片以便更好地理解 bot.hears('کلید ها', (ctx) => { request('http://127.0.0.1:8080/json.htm?type=command¶m=getlightswitches', function (error, response, body) { if (error == null) {
bot.hears('کلید ها', (ctx) => {
request('http://127.0.0.1:8080/json.htm?type=command¶m=getlightswitches', function (error, response, body) {
if (error == null) {
inputdevices = JSON.parse(body)
for (var key in inputdevices.result) {
ctx.reply(`${inputdevices.result[key].Name}`, Extra.HTML().markup((m) =>
m.inlineKeyboard([
m.callbackButton(`روشن`, `روشن کلید <%>${inputdevices.result[key].idx}<%> <#>${inputdevices.result[key].Name}<#>`),
m.callbackButton(`خاموش`, `خاموش کلید <%>${inputdevices.result[key].idx}<%> <#>${inputdevices.result[key].Name}<#>`)
])
)) .then(() => ctx.reply("*****************"))
}
}
else {
console.log("ارتباط با دیتابیس برقرار نشد ، لطفا دوباره تلاش کنید");
ctx.reply("ارتباط با دیتابیس برقرار نشد ، لطفا دوباره تلاش کنید")
}
})
})
bot.hears('{
请求('http://127.0.0.1:8080/json.htm?type=command¶m=getlightswitches,函数(错误、响应、正文){
如果(错误==null){
inputdevices=JSON.parse(正文)
for(inputdevices.result中的var键){
ctx.reply(`${inputdevices.result[key].Name}`,Extra.HTML().markup((m)=>
m、 内联键盘([
m、 callbackButton(`workوشن`、`workوشکلید${inputdevices.result[key].idx}${inputdevices.result[key].Name}`),
m、 callbackButton(`15825; 1605; 1608; 1588`、`15825; 1605; 1608; 1705; 1604; 1740; 1583${inputdevices.result[key].idx}${inputdevices.result[key].Name}`)
])
)).然后(()=>ctx.回复(“*******************”)
}
}
否则{
控制台日志;
ctx.答复
}
})
})
看这张照片
不符合规定:
假设ctx.reply()
返回一个承诺
,您需要将所有承诺链接在一起
不要对循环使用,而是做一些类似于递归函数的事情,一次调用一个对象。看起来您没有直接使用键
,因此我们还将首先映射到一个数组,以简化以下操作:
const arr = Object.keys(inputdevices.result).map(key => inputdevices.result[key]);
const replyNext = () => {
if (!arr.length) return Promise.resolve();
const inputDevice = arr.shift();
return ctx.reply(${inputDevice.Name}, Extra.HTML().markup((m) =>
m.inlineKeyboard([
m.callbackButton(روشن,روشن کلید <%>${inputDevice.idx}<%> <#>${inputDevice.Name}<#>),
m.callbackButton(خاموش,خاموش کلید <%>${inputDevice.idx}<%> <#>${inputDevice.Name}<#>)
])
)).then(() => ctx.reply("*****************"))
.then(replyNext);
}
请先修复代码格式。
Promise.all(
Object.keys(inputdevices.result)
.map(key => /* contents of your for loop, return promise */)
).then(() => console.log('all done'));