【问题标题】:Javascript - wait for async functions with new async functionsJavascript - 等待具有新异步函数的异步函数
【发布时间】:2015-12-01 09:54:05
【问题描述】:

问题:
是否可以等待启动新异步函数的异步函数?

详情:
我已经查找了很多方法来等待异步函数完成,然后再继续执行代码,或者运行特定的函数或代码块。但是有一件事困扰了我很长时间 - 我不知道是否也在等待新的异步函数启动,或者是否需要考虑他们自己的代码。

伪代码:

var value = 1;
af1();
alert(value);

async function af1(){
    af2();
}

async function af2(){
    af3();
}

async function af3(){
    value = 2;
}

我不知道这是否是一个很好的例子(甚至是正确的语法),但将异步函数想象成一些需要一些时间才能完成的 ajax 请求。我有一种感觉,如果你在 af1 上添加一个 jQuery deferred,它只会等待 af1 而忽略 af2 和 af3。我还为某些函数使用了外部 javascript 文件,但我无法真正控制在那里启动哪些新函数。

再说一遍,是否有可能将所有这些包装成一些东西并在完成后运行一些代码?还是我对 jQuery 的 deferred 和 .done 函数有误解??

【问题讨论】:

  • 你真的应该阅读 Promises。
  • 你应该检查github.com/caolan/async
  • "它将 […] 忽略 af2 和 af3" - 是的,当然,因为您甚至没有调用它们。您能否添加一些调用以使示例更加真实?
  • @mathkid91:谢谢,我调整了我的答案,现在更有意义了:-)

标签: javascript asynchronous async-await ecmascript-next


【解决方案1】:

不,async 函数在调用时不会等待。他们只是返回一个promise

async 函数内 - 这是他们的优势 - 您可以明确地 await 承诺,包括从其他 async 函数返回的承诺。

您的代码应该使用返回值编写,如下所示:

(async function() { // neccessary to use await
    value = await af1();
    alert(value);
}());
af1().then(alert); // or just using promise syntax

async function af1(){
    return af2();
}
async function af2(){
    return af3();
}
async function af3(){
    return 2; // or maybe rather something like
    return $.ajax(…);
}

但您不需要返回值,您也可以使用await 作为您的关闭方法:

(async function() {
    var value = 1;
    await af1();
//  ^^^^^
    alert(value);

    async function af1(){
        await af2();
    }
    async function af2(){
        await af3();
    }
    async function af3(){
        value = 2; // or maybe rather something like
        value = await $.ajax(…);
    }
}())

【讨论】:

  • 返回Promise 的函数就是我所说的异步,但并非所有异步函数都返回Promise。可以是基于回调、基于 CSP 等。
  • @BjörnRoberg:OP 正在谈论新的 ES7 提议的 async functions,它确实如此。我突出显示了该关键字,以表明我通常不是指异步函数。
  • 很高兴确认我必须处理每个功能。我想我将不得不尝试在我正在使用的库中挖掘一些内容。感谢您的回答!
  • @mathkid91:如果您使用的库不支持 Promise(或者至少不支持 A+ 兼容的 thenable,如 jQuery),请查看 promisification, i.e. converting a callback API to promises。否则,转译后的 async await 应该开箱即用。
【解决方案2】:

使用这个 git js ASync

如何使用

Async 提供了大约 20 个函数,包括通常的“功能性”嫌疑人(map、reduce、filter、each…)以及一些常见的异步控制流模式(parallel、series、falling…)。所有这些函数都假定您遵循 Node.js 约定,即提供单个回调作为异步函数的最后一个参数。

快速示例

async.map(['file1','file2','file3'], fs.stat, function(err, results){
    // results is now an array of stats for each file
});

async.filter(['file1','file2','file3'], fs.exists, function(results){
    // results now equals an array of the existing files
});

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

async.series([
    function(){ ... },
    function(){ ... }
]);

还有更多可用的功能,因此请查看以下文档以获取完整列表。该模块旨在全面,因此如果您觉得缺少任何内容,请为它创建一个 GitHub 问题。

Read More

【讨论】:

  • 谢谢你的回答 :) 既然评论中也提到了这个,我会查一下这是什么。
  • 如何将数据从 async.parallel 传递到 async.waterfall
【解决方案3】:

除了上面的例子,看看下面的代码示例。异步和等待的概念会更清楚。

async function doWork(){
    try {
        const response = await makeRequest('facebook'); //using await will wait until the response returned from the makeRequest function
        //console.log('Response Received' + response );

        const response2 = await makeRequest('google');
        //console.log('Response2 Received' + response2 );
    } catch(err) {
        alert(err);
    }
}

function makeRequest(str){
    //function body that takes time to process, eg: server call
    return "making request to " + str;
}

doWork();

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2011-03-04
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多