gpt4 book ai didi

node.js - ES5,如何在循环中使用 Promise

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:07 26 4
gpt4 key购买 nike

说 command_arr.length === 2

当我运行以下函数device_execute_command时。执行消息顺序为

finish one command
finish one command
has latest state?
has latest state?

我期望的是:

finish one command
has latest state?
finish one command
has latest state?

代码

var device_execute_command = function(command_arr) {
// This is the main loop
var i = 0;
for(i=0; i < command_arr.length; i++) {
var command = command_arr[i];
var command_id = command.command_id;

device_run_single_command(command).then(function(command){
console.log();
console.log("finish one command");
console.log(command);

return is_device_has_latest_state(command);
}).then(function(command_with_condi){
console.log();
console.log("has latest state?");
console.log(command_with_condi);

});


}

}

最佳答案

这是由于 javascript 的异步特性造成的。你要的就是一一兑现 promise 。这不能通过简单地在循环迭代中调用 Promise 来实现。实现这一点的最简单方法可能是使用 bluebird Promise 实现,它附带了许多用于 Promise 执行流程控制的方法。

例如,您的案例中的顺序执行可以通过以下方式实现:

const Promise = require('bluebird');

Promise.each(command_arr, function(command) {
return device_run_single_command(command).then(function(command) {
console.log();
console.log("finish one command");
console.log(command);
return is_device_has_latest_state(command);
}).then(function(command_with_condi) {
console.log();
console.log("has latest state?");
console.log(command_with_condi);
});
});

关于node.js - ES5,如何在循环中使用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36842277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com