Javascript-承诺保留为挂起状态

Javascript - Promises stay as pending

本文关键字:挂起状态 保留 承诺 Javascript-      更新时间:2023-09-26

为什么我的承诺保持挂起状态,我该如何修复它?

    var foundPeopleA = findPeopleA().then(function(result) {
        var res = []
        result.map(function(el) {
            res.push(getProfileXML(el.sid));
        });
        return res
    });
    var foundPeopleB = findPeopleB().then(function(result) {
        var res = []
        result.map(function(el) {
            res.push(getProfileXML(el.sid));
        });
        return res
    })
    return Promise.all([findPeopleA, findPeopleB]).then(function(results) {
        console.log(results) //[ [ Promise { <pending> }, Promise { <pending> } ],  [ Promise { <pending> }, Promise { <pending> } ] ]
    })

然而,如果我将上述2个功能的主体更改为

        var res
        result.map(function(el) {
            res = getProfileXML(el.sid);
        });
        return res

它们不会被挂起,我会得到结果的。

数组不是承诺。如果返回一个promise数组,then将获得一个promises数组,就像返回任何其他非promise值一样。只有当您返回一个promise时,该promise才会在then之前执行。您的foundPeopleAfoundPeopleB分别构建了一系列承诺;您需要将这些数组连接起来,并将它们传递给Promise.all或等效的数组,以便执行它们。

问题是,您使用then单独处理每个承诺的履行,而all通过向其传递一个未解决的承诺数组来处理多个承诺的履行。它用所有这些的结果建立了一个新的承诺。只需使用:

Promise.all([findPeopleA(), findPeopleB()])
.then(function(responses) ...

尝试将数组分配给映射的结果。

var foundPeopleA = findPeopleA().then(function(result) {
    var res = []
    res = result.map(function(el) {
        return getProfileXML(el.sid);
    });
    return res
});

或者,也许你可以兑现承诺?

var foundPeopleA = findPeopleA().then(function(result) {
    var res = []
    res = result.map(function(el) {
        return getProfileXML(el.sid);
    });
    resolve(res);
});

无论哪种方式,我认为您都需要通过返回映射中的值来创建新的数组。