简体   繁体   English

Javascript - 使用新的异步函数等待异步函数

[英]Javascript - wait for async functions with new async functions

Question:题:
Is it possible to wait for an async function that starts new async functions?是否可以等待启动新异步函数的异步函数?

Details:细节:
I have looked up a bunch of ways to wait for an async function to finish before continuing the code, or running a specific function or code block.在继续执行代码或运行特定函数或代码块之前,我已经查找了多种等待异步函数完成的方法。 But one thing have bugged me for a very long time - I do not know whether new async functions started are also being waited for, or if they require their own piece of code to be taken into account.但是有一件事困扰了我很长时间 - 我不知道是否也在等待新的异步函数启动,或者它们是否需要考虑自己的一段代码。

Pseudocode:伪代码:

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

async function af1(){
    af2();
}

async function af2(){
    af3();
}

async function af3(){
    value = 2;
}

I dont know if this is a good example (or even the right syntax), but picture the async functions as some ajax requests that takes some time to finish.我不知道这是否是一个很好的例子(甚至是正确的语法),但将异步函数想象为一些需要一些时间才能完成的 ajax 请求。 I have a feeling that if you add a jQuery deferred on af1, it will only wait for af1 and ignore af2 and af3.我有一种感觉,如果你在 af1 上添加一个 jQuery deferred,它只会等待 af1 而忽略 af2 和 af3。 I am also using an external javascript file for some of the functions, and I dont really have control over what new functions are started in there.我还为某些功能使用了外部 javascript 文件,但我无法真正控制在那里启动哪些新功能。

So again, is it possible to just wrap all of this into something and run some code after all is done?那么,是否有可能将所有这些都包装成一些东西并在完成后运行一些代码? Or am I mistaken about jQuery's deferred and .done functions??还是我对 jQuery 的延迟和 .done 函数有误解??

No, async functions are not awaited when called.不,调用时不等待async函数。 They just return a promise .他们只是回报一个承诺

Inside an async function - that's their advantage - you can explicitly await promises, including those that are returned from other async functions.async函数中——这是它们的优势——你可以显式地await承诺,包括那些从其他async函数返回的承诺。

Your code should have been written using return values, like this:您的代码应该是使用返回值编写的,如下所示:

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

But you don't need return values, you can use await as well for your closure approach:但是您不需要返回值,您也可以将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(…);
    }
}())

Use this git js ASync使用这个 git js ASync

How to use如何使用

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). Async 提供了大约 20 个函数,包括通常的“功能性”嫌疑(map、reduce、filter、each……)以及异步控制流的一些常见模式(并行、串行、瀑布……)。 All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your async function.所有这些函数都假定您遵循 Node.js 约定,即提供单个回调作为异步函数的最后一个参数。

Quick Examples快速示例

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(){ ... } ]);

There are many more functions available so take a look at the docs below for a full list.还有更多可用的功能,因此请查看下面的文档以获取完整列表。 This module aims to be comprehensive, so if you feel anything is missing please create a GitHub issue for it.本模块旨在提供全面性,因此如果您觉得缺少任何内容,请为其创建一个 GitHub 问题。

Read More阅读更多

Apart from above examples, look at below code sample.除了上面的例子,看看下面的代码示例。 concept of async and wait would be more clear.异步和等待的概念会更清楚。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM