如何按顺序运行两行Javascript-异步/承诺/回调 [英] How to run 2 lines of Javascript in sequence - async/promises/callbacks

查看:49
本文介绍了如何按顺序运行两行Javascript-异步/承诺/回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在香草javascript中按顺序运行两行(或更多行)代码.

I need to run two (or more) lines of code in sequence in vanilla javascript.

每个调用对例程的调用(又称为顶级函数,其目的是执行程序步骤而不是计算结果).这些依次呼叫其他多个人.

Each invokes calls to routines (aka top level functions, which have a purpose of performing procedural steps rather than calculating a result). These in turn call multiple others.

function fMasterProcedure() {
    fSubProcedure1();
    fSubProcedure2();
    ... etc
}

假设fSubProcedure1()的代码如下(对于此示例):

Suppose the code for fSubProcedure1() is as follows (for this illustration):

function fSubProcedure1() {
    fSubSubProcedure1_1();  // Normal
    fSubSubProcedure1_2();  // Async
    fSubSubProcedure1_3();  // Normal
    fSubSubProcedure1_4();  // Async
    fSubSubProcedure1_5();  // Normal
}

这实际上是与此处相同的问题如何在javascript中运行序列函数,尽管此处提供的答案并未说明如何执行,并且自那以来,有关promise和异步函数的语法已有更新.

This is literally the same question as here how to run sequence functions in javascript, although the answers provided there do not show how to do it, and there have been syntax updates in the years since in relation to promises and asynchronous functions.

这几天的答案似乎是promise and async/await ...还是只是不使用promise的回调?

These days the answer seems to be promises and async/await... or is it just callbacks without using promises?

我已经阅读了很多关于Promise的描述和教程,包括此处.

I have read many descriptions and tutorials on promises, including here.

但是,我最终得到这样的代码:

However, I end up with code like this:

function fMasterProcedure() {
    return (new Promise(function(resolve, reject) {
        fSubProcedure1();
        setTimeout(function () {
            resolve();
        }, 0);
    })).then(function(result) {
        fSubProcedure2();
    });
}

如您所见,它不必要地增加了400%的行,但仍无法可靠地工作.

As you can see, it adds 400% more lines unnecessarily and still doesn't work reliably.

有没有更有效的方式来编写此代码,或更合适的方式?

Is there a more efficient way to write this, or a more appropriate way?

(要求是在 fSubProcedure1 (及其任何子进程)完全完成之后运行 fSubProcedure2 .JS起作用"以这里是使JS达到该要求的方法").

(The requirement is to run fSubProcedure2 after fSubProcedure1 (and any of its child processes) are completed in full. I am trying to move from "that's not how JS works" to "here's how to make JS achieve that requirement").

我试图获得很好的理解,以便将其应用于整个项目方法-每个示例中都有很多示例.

I'm trying to get the good understanding so I can apply it to a whole project approach - there are many examples within, of each.

推荐答案

如果 fSubProcedure1 fSubProcedure2 是两个异步函数,您想一个接一个地执行它们,然后尝试去做类似的事情:

If fSubProcedure1 and fSubProcedure2 are two asynchronous functions and you wanna execute them one after the other then try to go for something like :

async function fMasterProcedure() {
    await fSubProcedure1();
    await fSubProcedure2()
}
// to execute the fMasterProcedure function
fMasterProcedure().then(console.log).catch(console.error);
//replace console.log and console.error with your appropriate callbacks

示例:

// returns Promise<number>
function fSubProcedure1() {
    console.log("runs first");
    return Promise.resolve(2*2);
}
// returns void
function fSubProcedureNormal() {
    console.log("runs second");
    //returns nothing
}
// returns number which gets converted to Promise<number>
async function fSubProcedure2() { 
    console.log("runs third");
    return 2*4;
}
async function fMasterProcedure() {
    let a = await fSubProcedure1();
    fSubProcedureNormal();
    let b = await fSubProcedure2();
    return `${a} : ${b}`;
}

fMasterProcedure().then(console.log).catch(console.error);

重要的一点...您想尝试在每次 await

One important point... You would wanna try and catch error inside fMasterProcedure for every await

资源:

异步功能

异步等待

查看这些资源以了解更多信息

Check out these resources to learn more

这篇关于如何按顺序运行两行Javascript-异步/承诺/回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆