鍍金池/ 問答/Java  Linux  HTML/ nodejs 如何同步執(zhí)行代碼并獲取返回值

nodejs 如何同步執(zhí)行代碼并獲取返回值

我有異步代碼段,這段代碼其實(shí)是 new Promise() 的對(duì)象,但是我需要多次循環(huán)這個(gè)對(duì)象同時(shí)獲取其中的值,代碼如下:

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);
};

上面的代碼的意思是根據(jù)configs.path來更新configs.branch;但是 nodegit 使用的是 Promise 同步執(zhí)行模式,請(qǐng)問我如何能獲取 Promise.then 的數(shù)據(jù),或者上面的代碼如何修改比較合適?謝謝!

難道我需要通過循環(huán)一層一層的 then 下去?

回答
編輯回答
涼汐

你的代碼沒什么大問題,主要是第二個(gè)configs[i]用錯(cuò)了,再了解一下Promise.all就知道怎么寫了;
參考代碼:

module.exports = function (options) {
    var nodegit = require("nodegit");
    var configs = [
        {
            "path": "path1",
            "branch": ""
        },
        {
            "path": "path2",
            "branch": ""
        }
    ];
    
    var getBranch = function(path){
        return nodegit.Repository.open(path).then(function (repo) {
            return repo.getCurrentBranch();
        })
    }
    
    var promises = configs.map(v=>{
        return getBranch(v.path).then(reference=>{
            v.branch = reference.name();
            return v;
        })
    })

    return Promise.all(promises)
};

@unicreators 的效率會(huì)差一點(diǎn)
@RandyO 的代碼和我的代碼意思差不多,只是那個(gè)All應(yīng)該是小寫

async/await是好東西,但建議先完全搞清楚Promise再使用.

2018年1月2日 09:21
編輯回答
涼汐

使用 es6 async/await

var nodegit = require("nodegit");
module.exports = async function (paths) {        
    let result = [];
    for (var i = 0; i < paths.length; i++) {
        let repo = await nodegit.Repository.open(paths[i]);
        let reference = await repo.getCurrentBranch();        
        result.push({ path: paths[i], reference, branch: reference.name() });
    }    
    return result;    
};

使用await調(diào)用

let result = await require('...')(['path1','path2', 'pathN']);
// or 
require('...')(['path1','path2', 'pathN']).then(result){
    // ...
}
2018年8月19日 07:56
編輯回答
絯孑氣

謝謝大神們的回復(fù)。這個(gè)問題基本上是按照我原來的寫法思路實(shí)現(xiàn)的,具體見 unicreators 下的評(píng)論。解決方案上是使用 Promise.all 實(shí)現(xiàn)。同時(shí)原則上如果不需要 return ,不要使用 async/await。

2018年4月16日 19:55
編輯回答
青黛色
var nodegit = require("nodegit");
module.exports = async function(options) {
    var configs = [{
        "path": "path1",
        "branch": ""
    }, {
        "path": "path2",
        "branch": ""
    }];
    var promises = []
    for (let i = 0; i < configs.length; i++) {
        promises.push(nodegit.Repository.open(configs[i].path));
    }

    const repos = await Promise.All(promises);

    for (let i = 0; i < configs.length; i++) {
        let reference  = await repos[i].getCurrentBranch();
        configs[i].branch = reference.name();
    }

    console.log(configs);
}
2017年7月14日 00:43