我有异步代码段,这段代码其实是 new Promise() 的对象,但是我需要多次循环这个对象同时获取其中的值,代码如下:
module.exports = function (options) {
var nodegit = require("nodegit");
var configs = [
{
"path": "path1",
"branch": ""
},
{
"path": "path2",
"branch": ""
}
];
for (var i = 0; i < configs.length; i++) {
nodegit.Repository.open(configs[i].path).then(function (repo) {
return repo.getCurrentBranch();
}).then(function (reference) {
configs[i].branch = reference.name();
return reference;
});
}
console.log(configs);
};
上面的代码的意思是根据configs.path来更新configs.branch;但是 nodegit 使用的是 Promise 同步执行模式,请问我如何能获取 Promise.then 的数据,或者上面的代码如何修改比较合适?谢谢!
难道我需要通过循环一层一层的 then 下去?
你的代码没什么大问题,主要是第二个
configs[i]
用错了,再了解一下Promise.all
就知道怎么写了;参考代码:
@unicreators 的效率会差一点
@RandyO 的代码和我的代码意思差不多,只是那个
All
应该是小写async/await
是好东西,但建议先完全搞清楚Promise
再使用.