父函数中的异步过程-返回异步过程结果?

时间:2019-02-27 18:51:10

标签: javascript asynchronous promise

我有一段代码在另一个函数中具有异步函数。在父函数中执行return语句之前,我需要等待该异步函数完成。我对Promise是陌生的,尽管我对stackoverflow进行了广泛的阅读,但我只是无法正确地获得顺序,因此在异步过程完成之前就执行了父函数的return语句。异步过程应该返回一个字符串,然后我想从父函数返回该字符串。我希望有人可以帮助我构造这个。

//Call the parent function
mgmtTractPopupBox.setContent(mgmtPopupContent);

function mgmtPopupContent(feature) {
    //set up query
    //Need this query to complete before executing "return content;" below
    //"relatedQuery" returns a deferred object, once that resolves, 
    //it enters the callback function.
    var content = queryableMgmtTractFL.queryRelatedFeatures(relatedQuery, relatedQueryComplete).then(function(value) {
        //This prints the result value of the relatedQuery promise (an Object), 
        //which is not what I need. I need the HTML string created in the
        //the relatedQueryComplete function.
        console.log(value);
    });
    //This executes before the asynchronous process has finished
    return content;
}

function relatedQueryComplete(relatedRecords) {
    return new Promise(function (resolve) {
        var content = '<table id="mgmtPopupTable1"><tr><th>Veg Mgmt Practice</th><th>Herbicide</th><th>Month</th><th>Year</th>\
            <th>Implemented By</th><th>Funded By</th><th>Farm Bill Code</th></tr>';
        //do stuff that adds to content variable
        content = content + '</table>';
        resolve(content);
    });
}

我了解到relatedQueryComplete应该返回一个承诺,并且在该承诺内我应该能够访问一个值,我认为这是我用来解决该承诺的content的值。我的.then()不会返回relatedQueryComplete的承诺值,而是返回relatedQuery的已解析值。我已经尝试过构建这样的承诺,但是没有成功:

var content = queryableMgmtTractFL.queryRelatedFeatures(relatedQuery).then(relatedQueryComplete).then(function(value){...}

很显然,我对诺言的理解被弄乱了。有人可以帮我正确地组织这个吗?另外-我确实需要向我的回调函数relatedQueryComplete传递一个额外的参数,但是...(relatedQuery, relatedQueryComplete(extraParam))...不能完成任务。我知道我需要像这样的包装器

callback(function(resultFromRelatedQuery){
   relatedQueryComplete(resultFromRelatedQuery, extraParam)
});

,但是resultFromRelatedQuery最终将成为relatedQuery延迟对象,而不是解析值。现在很困惑。

1 个答案:

答案 0 :(得分:0)

您可以使用最近添加的async/await功能。假设您有firstAsyncFunctionsecondAsyncFunction

async function secondAsyncFunction(param1, param2) {
    const result1 = await firstAsyncFunction();
    // do stuffs with result1, get a new result
    return resultFromSecondAsyncFunction;
}

然后您可以通过以下方式使用它:

secondAsyncFunction(param1, param2).then((resultFromSecondAsyncFunction) => {
    // do stuffs with resultFromSecondAsyncFunction...
});

await是关键字,它将使javascript“等待”,直到它从另一个异步函数获得结果以执行后续操作。

您可以在async/await上检出javascript.info/async-await,以了解更多信息。