如何在返回函数的变量之前等待Promise完成

如何在返回函数的变量之前等待Promise完成

这里的Promise是从异步函数返回的对象,可以基于前一个函数的结果添加callback方法。这样做是为了将函数的执行变成一个队列或者函数链。因此,作为队列中的函数,后续的函数必须等待前一个函数的结果。下面有两种常见的方式来实现这个目的。

  • 使用setTimeout()函数
  • 使用async或await()函数

使用 setTimeout() 函数: 为了在返回变量之前等待Promise完成,可以将函数设置为 setTimeout(), 这样函数将等待几毫秒。下面的程序将说明这种方法:

示例: 这个示例描述了使用 setTimeout()方法等待Promise完成之后再返回函数的变量。

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
 
function failureCallback() {
    console.log("This is failure callback");
}
 
wait(4 * 1000).then(() => {
    console.log("waited for 4 seconds");
    throw new Error("error occurred");
}).catch(() => {
    failureCallback();
});
 
wait(2 * 1000).then(() => console.log("waited for 2 seconds"));

输出:

如何在返回函数的变量之前等待Promise完成

使用asyncawait() 函数:

当无法确定 setTimeout() 所需的确切时间时,可以使用此方法。使用 async 关键字创建一个异步函数,该函数返回一个可能被拒绝或解决的 promise。如果该函数抛出了一个未捕获的异常,或者执行成功,promise 将被拒绝或解决。在异步函数内部使用 await 关键字来暂停其执行并等待 promise。下面的程序将说明这种方法:

示例:

该示例演示了在返回函数的变量之前使用 async/await 方法等待 promise 完成

// This function returns promise after 2 seconds
let first_function = function () {
    console.log("Entered first function");
    return new Promise(resolve => {
        setTimeout(function () {
            resolve("\t\t This is first promise");
            console.log("Returned first promise");
        }, 2000);
    });
};
 
// This function executes returns promise after 4 seconds
let second_function = function () {
    console.log("Entered second function");
    return new Promise(resolve => {
        setTimeout(function () {
            resolve("\t\t This is second promise");
            console.log("Returned second promise");
        }, 4000);
    });
};
 
let async_function = async function () {
    console.log('async function called');
 
    const first_promise = await first_function();
    console.log("After awaiting for 2 seconds," +
        "the promise returned from first function is:");
    console.log(first_promise);
 
    const second_promise = await second_function();
    console.log("After awaiting for 4 seconds, the" +
        "promise returned from second function is:");
    console.log(second_promise);
}
 
async_function();

输出:

async function called
Entered first function
Returned first promise
After awaiting for 2 seconds, the promise returned from first function is:
                 This is first promise
Entered second function
Returned second promise
After awaiting for 4 seconds, the promise returned from second function is:
This is second promise

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程