如何使这个异步函数同步

时间:2017-11-07 09:56:53

标签: javascript asynchronous

我调用以下函数:

function uploadReturns() {
    var uploads = me.getIssuesFromReturnsList();
    uploadreturnsobjects(uploads); //process the uploads object and send it to an AJAX call

}

me.getIssuesFromReturnsList中,在执行其余代码之前返回uploadList变量,因为它是异步的(根据this question

me.getIssuesFromReturnsList = function () {
    var uploadList = [];
    $.each(me.returnsList(), function (index, i) {
        var issue = issueRepository.GetDefaultIssue();
        issue.barcode = i.barcode;
        issue.ReturnsAmount(i.amount);

        var uploadItem = {
            barcode: i.barcode,
            amount: i.amount,
            issue: ko.observable(issue)
        };

        uploadList.push(uploadItem);

        issueRepository.GetIssuesOffline(i.barcode, function (issues) {
            if (issues.length > 0) {
                uploadItem.issue(issues[0]);
            }
        });
    });

    return uploadList;
}

如何更改此代码以使调用不再异步,而是在返回uploadList之前等待所有内部代码执行?

1 个答案:

答案 0 :(得分:-1)

使用Promises:

function forEachChain (array, func, thisArg) {
    const res = [];

    function exec(resolve, i) {
        func.call(thisArg, array[i]).then((e) => {
            res[i] = e;
            if (i < array.length - 1) {
                exec(resolve, i + 1);
            } else {
                resolve(res);
            }
        }, (err) => {
            res[i] = err;
            if (i < array.length - 1) {
                exec(resolve, i + 1);
            } else {
                resolve(res);
            }
        });
    }

    return new Promise((resolve) => {
        if (array.length > 0) {
            exec(resolve, 0);
        } else {
            resolve([]);
        }
    });
}

现在您可以调用此函数传递数组。对于该数组func的每个元素都被调用(由您传递),假设它也返回Promise

每次调用一次异步调用(并发版本稍微复杂一些)。

如果出现错误,则数组将包含相对索引处的相对错误。

forEachChain(myArray, myFuncReturningAPromise, thisArgInsideEachFuncCall).then((arrOfSameSizeOfMyArray) => { 
    // myCallback
}